Skip to content

Instantly share code, notes, and snippets.

@mariogarcia
Last active August 29, 2015 13:58
Show Gist options
  • Save mariogarcia/10352079 to your computer and use it in GitHub Desktop.
Save mariogarcia/10352079 to your computer and use it in GitHub Desktop.
Groovy version of the Haskell where clause
class FnCheck {
static class Evaluation {
Closure condition
Closure execution
}
def conditions = []
def parameters = [:]
def applyDelegateToCondition = { final parameters ->
return { final evaluation ->
evaluation.condition.delegate = parameters
evaluation
}
}
def applyDelegateToExecution = { final parameters ->
return { final evaluation ->
evaluation.execution.delegate = parameters
evaluation
}
}
def firstTrue = { evaluation -> evaluation.condition() }
def when(Closure cl) {
def createCondition = { closure -> new Evaluation(condition: closure)}
conditions << createCondition(cl)
return this
}
def rightShift(Closure value) {
then(value)
}
def then(Closure cl) {
conditions.last().execution = cl
return this
}
def otherwise(Closure cl) {
conditions << new Evaluation(condition: {true}, execution: cl)
}
def where (Closure whereClause) {
this.with(whereClause)
evaluate()
}
def propertyMissing(String name, value) {
parameters[name] = value
}
def evaluate() {
def applyDelegate = applyDelegateToCondition >> applyDelegateToExecution
def execution =
conditions.
collect(applyDelegate(parameters)).
find(firstTrue).execution
execution()
}
static Object check(Map values, Closure evaluation) {
def fnCheck = new FnCheck()
fnCheck.parameters = values
fnCheck.with(evaluation)
}
}
Map values = [height: 180, weight: 60]
//------------------------------------------
def result = FnCheck.check(values) {
when { weight <= underweight } then { "You're underweight" }
when { weight <= normal } then { "You're normal" }
when { weight <= fat } then { "You're fat" }
otherwise { "You have a strange composition" }
where {
underweight = 50
normal = 70
fat = 90
}
}
println "RESULT IS: $result"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment