Exemplary match in Erlang
I'm trying to learn some Erlang while I'm stuck with these few Erlang template issues. 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 got an empty list []
. I thought it was in line with the fifth article? Can this literal be an atom?
When I execute p1:f2([[a],[b], a])
, the result is equal ([b], [a])
, which means it matches the first sentence. However, I think that [a] and a are not the same thing? One is a list and the other is literal?
Also when I execute p1:f2([2, 7 div 3 > 2 | [5,3]])
it takes a value (2, false)
. I mean why is 7 div 3 > 2
it getting false? In another language like C or Java Yes I know 7 div 3 == 2
, which is why it makes this statement false. But is it the same in Erlang? Because I just tried this on the shell and it gives me 2.3333333..
which is more than 2
, so it will make this statement true. Can anyone provide an explanation?
source to share
it is because it [x]
is equal [x|[]]
, so it matches f2([_|B]) -> [B];
. As you can see B=[]
inn your case.
I think you did not write what you want. in the expression [A|B]
, A is the first item in the list and B is the rest of the list (so it's a list). This means [1,2,1]
it won't match [A1, A2 | A1]
; but [[1],2,1]
or [[a,b],1,a,b]
will.
source to share