Tuesday, March 29, 2011

Functional Inject & DSL

def l = [8,9,2,3,4,-1,5]

//max
println l.inject(l[0]) { last, next ->
    last > next ? last : next
}

//isEven
println l.inject([]) { l, n ->
   if (n % 2) l << n * 2
   else l
}
println l.collect{ if (it % 2) {it * 2} }.findAll{it}
println l.findAll{ it % 2 }.collect{ it * 2 }

def filtered = { list, f ->
  list.inject([]) { l, n ->
    if (f(n)) l << n
    else l
  }
}
println filtered(l, {true})
println filtered(l, { it % 2 })




class Mail {
  def to(String b) { println "To:$b" }
  def body(String b) { println "Body:\n$b" }
  def attachment(Object f) { println "Attachment:$f" }
  static send(doIt) {
      def mail = new Mail()
      mail.with doIt
      //mail.smtp()
  }
}

Mail.send {
    to 'Steven.Olsen'
    body 'Dear So And So,\n...\nSincerely!'
    attachment 'file/path/here.txt'
}

http://groovyconsole.appspot.com/script/449004

No comments:

Post a Comment