Is it possible to incorporate case statements in a lambda?

I'm trying to make a function that recursively adds two numbers recursively in Erlang with no luck.

Mult = fun(X) -> (fun(Y) -> case Y of  
  0 -> 0;
  Y -> X + fun(Y-1)
  end)
end. 

Receives error

syntax error before: 'end'
有帮助吗?

解决方案

Have a look at this page http://rosettacode.org/wiki/Y_combinator.

Applied to your case it gives:

1> Y = fun(M) -> (fun(X) -> X(X) end)(fun (F) -> M(fun(A) -> (F(F))(A) end) end) end.
#Fun<erl_eval.6.82930912>
2> Mul = fun (F) -> fun ({X,0}) -> 0; ({X,N}) -> X + F({X,N-1}) end end.
#Fun<erl_eval.6.82930912>
3> (Y(Mul))({5,4}).                                                     
20
4> 

I must confess it is a bit complex for me...

其他提示

You cannot use self declaration inside lambda (at least before R16) but you can send it as a parameter:

Mult = fun(X) ->
    YFun = fun(0, _) -> 0;
              (Y, M) ->
                  X + M(Y - 1, M)
           end,
    fun(Y) ->
        YFun(Y, YFun)
    end
end.

And you get

> (Mult(2))(3).
6

Remember that Erlang does pattern matching, even in anonymous functions. You don't really need a case statement here at all.

-module (math).
-export ([mult/1]).

mult(X) -> 
    fun(0) -> 0;
       (Y) -> X + (mult(X))(Y-1)
    end.

I don't think that the case expression in your code causes the problem. Rather the function definition itself is malformed.

If I interpret your code correctly, you want to define a recursive function for multiplication. And fun(Y-1) is intended as recursive function call?

But in your case Mult is a variable which is assigned an anonymous function (or rather two nested anonymous functions) and I don't think that anonymous functions allow for recursion.

How about the following variation:

-module (mult).
-export ([mult/1]).

mult(X) ->
  fun (Y) ->
    case Y of
      0 -> 0;
      Y -> X + (mult(X))(Y-1)
  end
end.

(to be put in a separate file).

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top