评估表达式

时间:2017-05-10 02:50:46

标签: erlang

我正在做一些过去的论文,需要知道我在这里是否正确。

逐步评估以下表达式:

foo(0,[2,3,1])
foo(0,[4,0,1])

其中foo的定义如下:

foo(_,[]) -> [];
foo(Y,[X|_]) when X==Y -> [X];
foo(Y,[X|Xs]) -> [X | foo(Y,Xs) ].

我的回答:

1

Foo(0, [2, 3, 1])
[2 | foo(0, 3, 1) ]
[2, 3| foo(0, 1) ]
[2, 3, 1 | foo (0)]
[2, 3, 1]

2

Foo(0, [4, 0, 1])
[4 | foo(0, 0,1])
[4, 0]

我在这里纠正吗?

1 个答案:

答案 0 :(得分:1)

至少函数参数是错误的,我会说:

1.

foo(0,[2,3,1])
[2|foo(0,[3,1])]        % 3rd clause
[2|[3|foo(0,[1])]]      % 3rd clause
[2|[3|[1|foo(0,[])]]]   % 3rd clause
[2|[3|[1|[]]]]          % 1st clause
[2,3,1]

2.

foo(0,[4,0,1])
[4|foo(0,[0,1])]        % 3rd clause
[4|[0]]                 % 2nd clause
[4, 0]