我想知道是否有可能为不同的参数类型(包括用户定义的类型)执行不同的功能。
这是我想要做的一个例子:
myfunction(myType i) ->
dothis;
myfunction(int s) ->
dothat.
这是可能的吗?如果可以的话,这样做的语法是什么?
答案 0 :(得分:4)
确实,erlang不提供定义类型的能力,但是可以认为类型可以是构建在主要erlang类型上的结构,例如类型answer
可以是{From, Time,List},在这种情况下,可以使用模式匹配和主要类型测试的混合:
myfunction({From,Time,List}) when is_pid(From), is_integer(Time), Time >= 0, is_list(List) ->
dothis;
myfunction(I) when is_integer(I) ->
dothat.
并且比您正在寻找的简单类型测试更接近,您可以使用宏进行测试
-define(IS_ANSWER(From,Time,List), (is_pid(From)), is_integer(Time), Time >= 0, is_list(List)).
myfunction({From,Time,List}) when ?IS_ANSWER(From,Time,List) ->
answer;
myfunction(I) when is_integer(I) ->
integer.
甚至
-define(IS_ANSWER(A), (is_tuple(A) andalso size(A) == 3 andalso is_pid(element(1,A)) andalso is_integer(element(2,A)) andalso element(2,A) >= 0 andalso is_list(element(3,A)))).
myfunction(A) when ?IS_ANSWER(A) ->
answer;
myfunction(A) when is_integer(A) ->
integer.
答案 1 :(得分:2)
您无法在Erlang中定义自己的数据类型,因此第一个子句是不可能的。您在 guard 中键入测试,因此第二个将成为:
my_function(S) when is_integer(S) ->
dothat.
guard 中的功能非常有限,它包含简单的测试,例如类型测试。阅读Guard Sequences。