|
or even¹ h = g.curry(2)[f]
h[1]
function composition is available: f = -> x { x * 2 }
g = -> y { y + 4 }
j = f >> g
k = j << g
j[1] #=> 6
k[1] #=> 14
and, topically, the Y combinator: y = -> f {
-> g { g[g] } [
-> g { f[-> v { g[g][v] }] }
]
}
hence fib = y[-> f {
-> n { n < 2 ? Array(0..n) : f[n-1].then { _1 << _1[-1] + _1[-2] } }
}]
fib[6] #=> [0, 1, 1, 2, 3, 5, 8]
although the more idiomatic Ruby might be fibo = Hash.new { |this, n| this[n] = n < 2 ? n : this[n-1] + this[n-2] }
(0..6).map(&fibo) #=> [0, 1, 1, 2, 3, 5, 8]
in which the Hash self-converts to a closure via the & operator.Anyone who says "Ruby doesn't have first-class functions" can fight me. -------------------- ⁽¹⁾ notwithstanding that I recall Matz once remarked the curry method is only included as an elaborate joke. |