class LazyList {
def head
private Closure tail
LazyList(def head, Closure tail) { this.head=head; this.tail=tail }
def LazyList getTail() { tail ? tail.call() : null }
def List getFirst(n) {
def result = []; def current = this
n.times { result.add(current.head); current = current.tail }
result
}
def LazyList filter(Closure matchExpr) {
if (matchExpr(head))
return matchExpr.owner.prepend(head, { getTail().filter(matchExpr) })
else
return getTail().filter(matchExpr)
}
}
// general purpose lazy list function
def prepend(val, Closure c) { new LazyList(val, c) }
class User
{
def age = 0
def id = 0
def name = 'default '
User plus(def i)
{
def p = 'and marc son bert wick ness ton shire step ley ing sley up down jack ly rex sum brown'.split()
def q = 'Lord Lady Viscount Baronet Marquis Sir Captain Admiral'.split()
def random = q[new Random().nextInt(q.size())] + ' ' + (0..1).collect { p[new Random().nextInt(p.size())] }.join('').capitalize() + ' ' + (0..1).collect { p[new Random().nextInt(p.size())] }.join('').capitalize()
new User(age:this.age+i,id:this.id+i,name:random)
}
String toString()
{
name+' '+age+' '+id
}
}
// now define and use infinite streams
def userFactory(n) { prepend(n, { userFactory(n+1) }) }
def listOfUsers = userFactory(new User().plus(1))
def ten = listOfUsers.getFirst(10)
println ten
def evennumbers =listOfUsers.filter{ it.age % 2 == 0 }
println evennumbers.getFirst(10)
torsdag 16 januari 2014
Infinite List with Groovy used as object factory
Prenumerera på:
Kommentarer till inlägget (Atom)
Inga kommentarer:
Skicka en kommentar