Background
For the longest time I have been estranged to the magic lands of comprehensions in FP languages.
Now I am trying to pick it up.
Comprehensions use the for
expression in Elixir:
How Scala does it
Most FP languages these days have comprehensions in one way or another. For the purposes of this discussion I am picking Scala because I think it looks somewhat familiar (syntax is fairly similar to that of elixir).
See the following comprehension (Scala):
for {
a <- List(1, 2)
b <- Set(2, 1)
} yield a * b
> List(2, 1, 4, 2)
This comprehension is the equivalent of (Elixir):
for a <- [1, 2],
b <- MapSet.new([2, 1]) do
a * b
end
> [1, 2, 2, 4]
The Scala example returns a List
because in Scala, the comprehension’s return type will be the type of the first enumerator (in this case a <- [1, 2]
).
The Elixir example returns also a List
. I have no idea why. Maybe they work in reverse? Let’s find out:
for {
a <- Set(1, 2)
b <- List(2, 1)
} yield a * b
> Set(2, 1, 4)
In this Scala example I switched things around. Lets see what Elixir returns:
for a <- MapSet.new([1, 2]),
b <- [2, 1] do
a * b
end
> [2, 1, 4, 2]
It also returns a List
…
Questions
So, I am rather confused here. So here is my question:
- In an Elixir comprehension with enumerators of different types, how do I know what the resulting type of the expression will be?