Comprehending List Comprehensions
Hakan Mattsson
hakan@REDACTED
Mon Nov 26 13:36:17 CET 2001
On Mon, 26 Nov 2001, Peter Caven wrote:
Peter> I am at the early stages of learning Erlang and I've encountered what seems
Peter> to be strange behaviour in list comprehensions. The expression:
Peter>
Peter> [{Token} || {Start, Length} <- [{1,1},{2,2},{4,2}], Token <-
Peter> string:substr("1+1-2", Start, Length)]
Peter>
Peter> returns:
Peter>
Peter> [{49},{43},{49},{45},{50}]
Peter>
Peter> when I expected it to return:
Peter>
Peter> [{"1"},{"+1"},{"-2"}]
Peter>
Peter> Can someone please point out where my mistake is?
The Token generator with contribute with a solution for each element
in the list that string:substr/2 returns. See this little example:
5> [Token || Token <- string:substr("1+1-2", 1, 1)].
"1"
6> [{Token} || Token <- string:substr("1+1-2", 1, 1)].
[{49}]
7> [{Token} || Token <- string:substr("1+1-2", 1, 2)].
[{49},{43}]
8> [{Token} || Token <- string:substr("1+1-2", 1, 3)].
[{49},{43},{49}]
You problably intended to do this:
9> [{string:substr("1+1-2", Start, Length)} || {Start, Length} <- [{1,1},{2,2},{4,2}]].
[{"1"},{"+1"},{"-2"}]
10>
/Håkan
---
Håkan Mattsson
Ericsson
Computer Science Laboratory
http://www.ericsson.com/cslab/~hakan/
More information about the erlang-questions
mailing list