Mukul Chakravarty
Mukul Chakravarty

Reputation: 193

Elixir list comprehension

I have a list of tuples :

m=[{5, 3}, {6, 6}, {7, 10}]

Now I want to create a second list such that for each tuple of values inside m I will insert "A" if first value>second value and "B" if first < second. So in this case the list will result in ["A","B"] ( since 5>3 and 7<10) I used the following code :

res= for {u,v} <- m do if u>v do "A" end
                       if u<v do "B" end 
                    end

However it is resulting in the following :

[nil, nil, "B"]

I am not able to figure out what is wrong ? Thanks in advance

Upvotes: 1

Views: 767

Answers (2)

aryndin
aryndin

Reputation: 591

It's just a matter of couple of commas:

iex(252)> res= for {u,v} <- m, do: if u>v, do: "A", else: "B"
["A", "B", "B"]

Upvotes: 0

Dogbert
Dogbert

Reputation: 222080

I am not able to figure out what is wrong?

Your first if expression is being ignored completely by the compiler because you have another expression after that (you should get a warning if you compile this in a Mix project). Elixir only returns the value of the last expression, which in this case is either "B" (when u < v) or nil otherwise.

You can either use else with if or cond here so that there's only one expression in the do:

res = for {u,v} <- m do
  if u > v do
    "A"
  else
    "B"
  end
end

or

res = for {u,v} <- m do
  cond do
     u > v -> "A"
     u < v -> "B"
  end
end

Note that the first one will return "B" if u == v and the second one will raise an exception if u == v. I'm not sure which one you want.

Upvotes: 3

Related Questions