在Elixir中将保护子句与Timex DateTime一起使用

Tho*_*wne 2 elixir

因此,我可以根据参数的类型使用保护子句来运行函数的不同版本:

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
Run Code Online (Sandbox Code Playgroud)

但是,如果我想基于Timex.Datetime类型放置保护子句,例如:

iex(5)> Timex.now  
#DateTime<2018-03-16 12:36:24.061549Z>
Run Code Online (Sandbox Code Playgroud)

我似乎无法找到Timex.is_datetime函数或等效函数。

Ale*_*kin 5

DateTime是底层的裸露结构。在Erlang中(因此在Elixir中),可以使用模式匹配函数参数:

def double(%DateTime{} = x)
Run Code Online (Sandbox Code Playgroud)

上面的内容只要x有一个DateTimestruct 就会匹配。对于内置类型(例如整数),没有这样的表示法,因此使用了防护措施。但是,对于二进制文件,可以使用Kernel.SpecialForms.<<>>/1:

def double(<< x::binary >>)
Run Code Online (Sandbox Code Playgroud)

大致与:

def double(x) when is_binary(x)
Run Code Online (Sandbox Code Playgroud)

列表和地图的模式匹配如下:

def double([]) do     # empty list
def double([h|t]) do  # non-empty list
def double(%{}) do    # any map (NB! not necessarily empty)
Run Code Online (Sandbox Code Playgroud)

另外,可能会在地图中图案化匹配键:

def double(%{foo: foo} = baz) do
  IO.inspect({foo, baz})
end
double(%{foo: 42, bar: 3.14})
#? {42, %{foo: 42, bar: 3.14}}
Run Code Online (Sandbox Code Playgroud)