Reputation: 351
I have a simple function like this:
def currencyConverter({ from, to, amount }) when is_float(amount) do
result = exchangeConversion({ from, to, amount })
exchangeResult = resultParser(result)
exchangeResult
end
I want to guarantee that from and to are strings and amount are float, and if not, display send a customize error message instead erlang error What's the best way to do this?
Upvotes: 0
Views: 283
Reputation: 447
you can make two functions with same name and arity, one with guards and one without
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"
If you want to check the input type, you will need to create a function to do it because elixir does not have a global one.
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
(typeof/1 function is based on this post:https://stackoverflow.com/a/40777498/10998856)
Upvotes: 1