views:

77

answers:

2

Hi everyone,

I have a little issue to which I can find no easy answer.

I set:

Who = apple.

Message = [{apple, {0,0,0}}, {orange, {1,1,1}}].

Old = [X || {Who, X} <- Message].

Old returns as [{0,0,0},{1,1,1}]

Of course my expected response was {0,0,0}

Instead I get both apple and orange.

What could I do??

+3  A: 

Interesting question, I really liked that one! Looks like the scoping rules of Erlang are a bit odd (or at least I am not used to it, because I don't use Erlang regularly)... But the following seems to work:

[Old|_] = [X || {W, X} <- Message, W =:= Who].
tux21b
I would prefer `=:=` in this case.
Hynek -Pichi- Vychodil
Does it matter in this case? Can atoms be nearly equal? Anyway I've updated it.
tux21b
+4  A: 

This is actually the same question as in http://stackoverflow.com/questions/1277867/why-erlang-variable-is-unused where I gave an answer. Basically it is because all patterns variables in comprehensions are new, fresh variables so if you want to test them you need to do it explicitly. It is same as for variables occurring in the head of funs.

rvirding