Recursion and anonymous functions in elixir

前端 未结 4 2016
我寻月下人不归
我寻月下人不归 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:47

    You could define a module-function called fix, and use it later to define dot (and any other recursing anonymous function):

    defmodule A do
        def fix(f, x) do
          f.(fn(x) -> fix(f, x) end, x)
        end
    
        def fix2(f, x, y) do
          f.(fn(x, y) -> fix2(f, x, y) end, x, y)
        end
    end
    
    dot = fn(x, y) ->
        A.fix2(fn
              dot, [i|input],[w|weights], acc -> dot.(input,weights,i*w+acc)
              dot, [],[bias],acc -> acc + bias
        end, x, y)
    end
    

提交回复
热议问题