【问题标题】:Using a guard clause with a Timex DateTime in Elixir在 Elixir 中使用带有 Timex DateTime 的保护子句
【发布时间】:2018-03-16 21:12:50
【问题描述】:

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

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 函数或等效函数。

【问题讨论】:

  • 模式匹配直接在函数子句中代替:def double(%DateTime{} = x) do.
  • @mudasobwa 啊哈。这也适用于内置类型吗?

标签: elixir


【解决方案1】:

DateTime 是下面的裸结构。在 Erlang 中(因此在 Elixir 中),可以对函数参数进行模式匹配:

def double(%DateTime{} = x)

只要xDateTime 结构,上述内容就会匹配。对于像整数这样的内置类型,没有这样的表示法,因此使用了守卫。不过,对于二进制文件,可以使用Kernel.SpecialForms.&lt;&lt;&gt;&gt;/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)

另外,也可以在地图中匹配 keys

def double(%{foo: foo} = baz) do
  IO.inspect({foo, baz})
end
double(%{foo: 42, bar: 3.14})
#⇒ {42, %{foo: 42, bar: 3.14}}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多