lambdas中的case语句(case statements in lambdas)

是否可以将案例陈述纳入lambda?

我正在尝试创建一个函数,递归地在Erlang中递归地添加两个数字而没有运气。

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

收到错误

syntax error before: 'end'

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'

最满意答案

看看这个页面http://rosettacode.org/wiki/Y_combinator 。

适用于您的情况,它给出:

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>

我必须承认这对我来说有点复杂......

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...

lambdas中的case语句(case statements in lambdas)

是否可以将案例陈述纳入lambda?

我正在尝试创建一个函数,递归地在Erlang中递归地添加两个数字而没有运气。

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

收到错误

syntax error before: 'end'

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'

最满意答案

看看这个页面http://rosettacode.org/wiki/Y_combinator 。

适用于您的情况,它给出:

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>

我必须承认这对我来说有点复杂......

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...