Skip to content

Instantly share code, notes, and snippets.

@fsword
Last active August 29, 2015 14:03
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save fsword/328df48c32eff61d8d56 to your computer and use it in GitHub Desktop.
Y Combinator
#!/usr/bin/env escript
main(_Args) ->
Y = fun(Generator) ->
Gen = fun(X) ->
fun(Args) ->
(Generator(X(X)))(Args)
end
end,
Gen(Gen)
end,
Fac = Y(fun(Callback) ->
fun(Arg) ->
if
Arg =< 1 -> 1;
true -> Arg * Callback(Arg-1)
end
end
end),
Fib = Y(fun(Callback) ->
fun(Arg) ->
if
Arg =< 1 -> 1;
true -> Callback(Arg - 1) + Callback(Arg - 2)
end
end
end),
io:format("~p~n~p~n", [Fac(5), Fib(5)]).
#!/usr/bin/env ruby
def y
->(gen){gen[gen]}[
->(x){->(args){yield(x[x])[args]}}
]
end
fac = y do |callback|
->(i){i <= 1 ? 1 : callback[i-1] * i}
end
fib = y do |callback|
->(i){i <= 1 ? 1 : callback[i-1] + callback[i-2]}
end
puts "#{fac[5]}\n#{fib[5]}"
@fsword
Copy link
Author

fsword commented Jul 10, 2014

ruby 代码说明:

  • lamdba{|x| dosth} 等价于 ->(x){dosth}
  • func.call(args) 等价于 func[args]

@fsword
Copy link
Author

fsword commented Jul 10, 2014

revision 4变更说明: 使用函数定义ycombinator,借助yield/block机制简化代码

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment