pattern match in Erlang

2019-08-10 13:56发布

问题:

I am trying to learn some Erlang while I got stuck on these several Erlang pattern matching problems. Given the module here:

-module(p1).
-export([f2/1]).

f2([A1, A2 | A1]) -> {A2, A1};
f2([A, true | B]) -> {A, B};
f2([A1, A2 | _]) -> {A1,A2}; 
f2([_|B]) -> [B];
f2([A]) -> {A}; 
f2(_) -> nothing_matched.

and when I execute p1:f2([x]), I received an empty list which is []. I thought it matches the 5th clause? Is that a literal can also be an atom?

When I execute p1:f2([[a],[b], a]), the result is ([b], [a]) which means it matches the first clause. However I think [a] and a are not the same thing? One is a list but the other is a literal?

Also when I execute p1:f2([2, 7 div 3 > 2 | [5,3]]) it evaluates to (2, false). I mean why 7 div 3 > 2 gets to be false? In other language such as C or Java Yeah I know 7 div 3 == 2 so it makes this statement false. But is it the same in Erlang? Because I just tried it on shell and it gives me 2.3333333.. which is larger than 2 so it will make this statement true. Can someone gives an explaination?

回答1:

it is because [x] is equal to [x|[]] so it matches f2([_|B]) -> [B];. As you can see B=[] inn your case.

I think you didn't write what you want to do. in the expression [A|B], A is the first element of the list, while B is the rest of the list (so it is a list). That means that [1,2,1] will not match [A1, A2 | A1]; but [[1],2,1] or [[a,b],1,a,b] will.



回答2:

First, 7 div 3 is 2. And 2 is not greater than 2, it's equal.

Secondly, [x, y] = [x | [y] ], because the right (or rest) part is always a list. That's why you get in the first clause.