Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elixir case on a single line

Tags:

elixir

I would like to have the following case on a single line:

case s do
  :a -> :b
  :b -> :a
end

The macro case is defined as case(condition, clauses). The following

quote do
  case s do
    :a -> :b
    :b -> :a
  end
end

gives:

{:case, [],
 [{:s, [], Elixir}, [do: [{:->, [], [[:a], :b]}, {:->, [], [[:b], :a]}]]]}

and from here should be possible to go back to case(s, ???)

like image 525
PeptideChain Avatar asked Feb 14 '17 15:02

PeptideChain


2 Answers

There are two possible ways to do this. One from the answer above is to inline the do end calls obtaining:

case s do :a -> :b; :b -> :a end

Another one is to use , do: keyword version of a block. We need to group the two expressions - otherwise the compiler wouldn't know both clauses are part of the case:

case s, do: (:a -> :b; :b -> :a)

Without the parens the expression would be parsed as:

(case s, do: :a -> :b); :b -> :a

And :b -> :a on it's own is not a valid expression in elixir.

like image 88
michalmuskala Avatar answered Oct 31 '22 01:10

michalmuskala


Apparently, you can use ; to achieve what you want:

 case s do :a -> :b; :b -> :a end
like image 24
Frank Schmitt Avatar answered Oct 31 '22 01:10

Frank Schmitt