Y combinator: Difference between revisions

Content added Content deleted
(→‎{{header|SuperCollider}}: clarify why we need z to make the call lazy)
(Add lang example)
Line 3,815: Line 3,815:
-> 34
-> 34


</syntaxhighlight>

=={{header|Lang}}==
Y combinator function:
<syntaxhighlight lang="lang">
# Disable warning for shadowing of predefined function
lang.errorOutput = -1

fp.combY = (fp.f) -> {
# fp.f must be provided by the function with a partially called combinator function, because fp.f will not be available in the callee scope
fp.func = (fp.f, fp.x) -> {
fp.callFunc = (fp.f, fp.x, &args...) -> return fp.f(fp.x(fp.x))(&args...)
return fn.combAN(fp.callFunc, fp.f, fp.x)
}
return fn.combM(fn.combA2(fp.func, fp.f))
}

# Re-enable warning output
lang.errorOutput = 1
</syntaxhighlight>

Usage (Factorial):
<syntaxhighlight lang="lang">
fp.fac = (fp.func) -> {
fp.retFunc = (fp.func, $n) -> {
return parser.op($n < 2?1:$n * fp.func(parser.op($n - 1)))
}
return fn.combAN(fp.retFunc, fp.func)
}

# Apply Y combinator
fp.facY = fp.combY(fp.fac)

# Use function
fn.println(fp.facY(10))
</syntaxhighlight>

Usage (Fibonacci):
<syntaxhighlight lang="lang">
fp.fib = (fp.func) -> {
fp.retFunc = (fp.func, $x) -> {
return parser.op($x < 2?$:fp.func(parser.op($x - 2)) + fp.func(parser.op($x - 1)))
}
return fn.combAN(fp.retFunc, fp.func)
}

fp.fibY = fp.combY(fp.fib)

fn.println(fp.fibY(10))
</syntaxhighlight>
</syntaxhighlight>