因此,我可以根据参数的类型使用卫士子句运行不同版本的函数:
iex(2)> defmodule Test do
...(2)>
...(2)> def double(x) when is_integer(x) do
...(2)> x * 2
...(2)> end
...(2)>
...(2)> def double(x) when is_binary(x) do
...(2)> String.to_integer(x) * 2
...(2)> end
...(2)> end
iex(3)> Test.double(2)
4
iex(4)> Test.double("2")
4但是,如果我想根据Timex.Datetime类型放置一个卫士子句怎么办,如:
iex(5)> Timex.now
#DateTime<2018-03-16 12:36:24.061549Z>我似乎无法找到一个Timex.is_datetime函数或类似的函数。
发布于 2018-03-16 12:44:10
DateTime是一个底层的结构。在Erlang中(因此在Elixir中),可以使用模式匹配函数参数:
def double(%DateTime{} = x)只要x是DateTime结构,上面的内容就会匹配。对于内置类型,如整数,没有这样的表示法,因此使用了保护。但是,对于二进制文件,可以使用Kernel.SpecialForms.<<>>/1
def double(<< x::binary >>)大致与以下几点相同:
def double(x) when is_binary(x)列表和地图可能与模式匹配如下:
def double([]) do # empty list
def double([h|t]) do # non-empty list
def double(%{}) do # any map (NB! not necessarily empty)此外,还可以在地图中使用模式匹配键:
def double(%{foo: foo} = baz) do
IO.inspect({foo, baz})
end
double(%{foo: 42, bar: 3.14})
#⇒ {42, %{foo: 42, bar: 3.14}}https://stackoverflow.com/questions/49320977
复制相似问题