我有一个这样的简单函数。
def currencyConverter({ from, to, amount }) when is_float(amount) do
result = exchangeConversion({ from, to, amount })
exchangeResult = resultParser(result)
exchangeResult
end
我想保证from和to是字符串,金额是float,如果不是,就显示发送一个自定义的错误信息,而不是erlang error什么是最好的方法?
你可以用相同的名字和同位数制作两个函数,一个带守卫,一个不带守卫。
def currencyConverter({from, to, amount}) when is_float(amount) and is_bitstring(to) and is_bitstring(from) do
result = exchangeConversion({ from, to, amount })
exchangeResult = resultParser(result)
exchangeResult
end
def currencyConverter(_), do: raise "Custom error msg"
如果你想检查输入类型,你需要创建一个函数来实现,因为elixir没有一个全局的函数。
def currencyConverter({from, to, amount}) when is_float(amount) and is_bitstring(to) and is_binary(from) do
result = exchangeConversion({ from, to, amount })
exchangeResult = resultParser(result)
exchangeResult
end
def currencyConverter({from, to, amount}) do
raise """
You called currencyConverter/1 with the following invalid variable types:
'from' is type #{typeof(from)}, need to be bitstring
'to' is type #{typeof(to)}, need to be bitstring
'amount' is type #{typeof(amount)}, need to be float
"""
end
def typeof(self) do
cond do
is_float(self) -> "float"
is_number(self) -> "number"
is_atom(self) -> "atom"
is_boolean(self) -> "boolean"
is_bitstring(self)-> "bitstring"
is_binary(self) -> "binary"
is_function(self) -> "function"
is_list(self) -> "list"
is_tuple(self) -> "tuple"
true -> "ni l'un ni l'autre"
end
end
(typeof1函数是基于这个帖子的。https:/stackoverflow.coma4077749810998856)。)