Recursion and anonymous functions in elixir

前端 未结 4 1938
我寻月下人不归
我寻月下人不归 2021-02-03 19:52

I\'m trying to define an anonymous function to do a dot product, I can code this as a private function without any problem but I am struggling with the anonymous function syntax

4条回答
  •  时光说笑
    2021-02-03 20:48

    Here's a fixed (Y) combinator:

    fix = fn f -> 
        (fn z ->
            z.(z)
        end).(fn x -> 
            f.(fn y -> (x.(x)).(y) end)
        end)
    end
    

    Here's how you use it:

    factorial = fn factorial ->
        fn
            0 -> 0
            1 -> 1
            number -> number * factorial.(number - 1)
        end
    end
    
    fix.(factorial).(6) # 720
    

    Only works with functions that recurse with 1 argument. Elixir doesn't have variable arguments. To support multiple arguments, you'll need to add more arguments than the single y like: f.(fn a,b -> (x.(x)).(a,b) end).

提交回复
热议问题