在Erlang中为模式匹配设置相同的变量意味着值是否相同?

时间:2018-03-22 22:58:22

标签: erlang pattern-matching

我有一些像这样的代码:

typeof

我可以通过这样做来摆脱function countTheObjects(arr) { let count = 0; for (let i = 0; i < arr.length; i++) { if (arr[i] instanceof Object && !Array.isArray(arr[i])) { count++; } } return count; } console.log(countTheObjects([]) === 0); console.log(countTheObjects([1, 3, 4, 5]) === 0); console.log(countTheObjects([1, 3, 4, 5, 'foo']) === 0); console.log(countTheObjects([1, 3, 4, 5, {}, {}, {}, 'foo']) === 3); console.log(countTheObjects([1, [], 3, 4, 5, {}, {}, {}, 'foo']) === 3); console.log(countTheObjects([1, [], null, 3, 4, 5, {}, {}, {}, 'foo']) === 3); console.log(countTheObjects([1, {}, [], null, null, 'foo', 3, 4, 5, {}, {}, {}, 'foo']) === 4);子句:

hdistance([H|T], [H1|T1], Distance) when H /= H1 ->
        hdistance(T, T1, Distance + 1);

hdistance([H|T], [H1|T1], Distance) when H == H1 ->
        hdistance(T, T1, Distance).

如果是,为什么,如果没有,为什么不呢?

1 个答案:

答案 0 :(得分:4)

Yes.

If yes why

Based on my experience with maps, I remember formulating a rule that the order of matching is not guaranteed, but once one of the lists matches and H is bound to a value, then the other list will only match if the head of the list is equal to H.

You may have experienced something similar in the shell when you wrote:

2> X = 10.

then sometime later, you wrote:

5> X = 20.

and you got an error that said, "no match of right hand side". For the first "match", X was bound to 10; then for the second match because 20 does not match 10, you get an error. It works the same way for your lists: H gets bound to a value for the first match, then for the second match the head of the list has to equal H.

You can actually write the second clause like this:

hdistance([_|T], [_|T1], Distance) ->
        hdistance(T, T1, Distance).

because execution will only get to the second clause if the heads of the lists are not equal.