Elixir case on a single line

家住魔仙堡 提交于 2019-12-22 04:06:04

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!