Erlang/OTP Forums

Author Message

<  Erlang  ~  List Comprehensions: [] gives me an unexpected result

bluefly
Posted: Sun Jan 13, 2008 5:59 pm Reply with quote
User Joined: 06 Jan 2008 Posts: 10
This may reflect my lack of comprehension of list comprehensions, but here is something I did not expect... First, a normal list comprehension:
Code:
erl> [ [X, Y] || X <- [1, 2, 3], Y <- [4] ].
[[1,4],[2,4],[3,4]]
I asked myself, what if Y was an empty list? I expect [1, 2, 3]. Instead:
Code:
erl> [ [X , Y] || X <- [1, 2, 3], Y <- [] ].
[]
Similarly, if I swap who is empty,
Code:
erl> [ [X , Y] || X <- [], Y <- [1, 2, 3] ].
[]
I tried framing my results as tuples and received the same empty set result. Why is my result []? Is this a desired behavior?
View user's profile Send private message
Mazen
Posted: Wed Jan 16, 2008 9:34 am Reply with quote
User Joined: 20 Jul 2006 Posts: 164 Location: London
I don't know for a fact if this is good or bad but it is logical and since logic is considered a good thing then I guess it is desirable Smile

The number of possible combinations is LengthX * LengthY and if LengthY = 0 then I guess the whole thing is 0. If you would do the equivalent thing in a for each loop it would look somewhere along the line of this:
Code:

foreach X in ListX
    foreach Y in ListY
       Store {X,Y}
    end
end


I.e. neither the outer or inner list must be of length 0.

I hope I'm making sense hehe

/Mazen
View user's profile Send private message

Display posts from previous:  

All times are GMT
Page 1 of 1
This forum is locked: you cannot post, reply to, or edit topics.

Jump to:  

You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum
You cannot attach files in this forum
You cannot download files in this forum