问题
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, ???)
回答1:
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.
回答2:
Apparently, you can use ;
to achieve what you want:
case s do :a -> :b; :b -> :a end
来源:https://stackoverflow.com/questions/42229946/elixir-case-on-a-single-line