【发布时间】: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