Skip to content

Instantly share code, notes, and snippets.

@bga
Created September 22, 2011 13:09
Show Gist options
  • Save bga/1234722 to your computer and use it in GitHub Desktop.
Save bga/1234722 to your computer and use it in GitHub Desktop.
declarative style evaluation.js
/*
Declarative style evaluation.
Advantages
order of evaluation is not important
evaluation is lazy i.e. its evaluated only if required
auto memorization of evaluation (only for pure fns)
expressions are writed as in math, no mutable values
*/
Object.prototype._let = #(name, _calc) {
fix self = @
@__defineGetter__(name, #{
var ret = _calc()
delete @[name] // memo result
@[name] = ret
-> ret
})
}
fix _solveQuadraticEquation = #(a, b, c) {
with({})
{
_let('D', #{ -> b*b - 4*a*c })
_let('x1', #{ -> (-b + Math.sqrt(D)) / (2*a) })
_let('x2', #{ -> (-b - Math.sqrt(D)) / (2*a) })
if(D < 0)
-> []
else if(D == 0)
-> [x1]
else
-> [x1, x2]
}
}
_log(_solveQuadraticEquation(1, 0, -1))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment