是否可以在Erlang中按类型匹配参数?

是否可以在Erlang中按类型匹配参数?,erlang,Erlang,我想知道是否有可能有一个函数对不同的参数类型(包括用户定义的类型)执行不同的操作 这是我想做的一个例子: myfunction(myType i) -> dothis; myfunction(int s) -> dothat. 这可能吗?如果可能,那么执行此操作的语法是什么?您无法在Erlang中定义自己的数据类型,因此第一个子句是不可能的。您在防护装置中进行了型式试验,因此第二个将成为: my_function(S) when is_integer(S) ->

我想知道是否有可能有一个函数对不同的参数类型(包括用户定义的类型)执行不同的操作

这是我想做的一个例子:

myfunction(myType i) ->
    dothis;
myfunction(int s) ->
    dothat.

这可能吗?如果可能,那么执行此操作的语法是什么?

您无法在Erlang中定义自己的数据类型,因此第一个子句是不可能的。您在防护装置中进行了型式试验,因此第二个将成为:

my_function(S) when is_integer(S) ->
    dothat.

在guard中可以做的事情非常有限,它包括简单的测试,例如类型测试。阅读。

您无法在Erlang中定义自己的数据类型,因此第一个子句是不可能的。您在防护装置中进行了型式试验,因此第二个将成为:

my_function(S) when is_integer(S) ->
    dothat.

在guard中可以做的事情非常有限,它包括简单的测试,例如类型测试。Erlang不提供定义类型的能力,但是可以考虑一种类型是基于主Erlang类型构建的结构,例如,类型<代码>回答<代码>可以是{,从,时间,列表}的形式,在这种情况下,可以使用模式匹配和主类型测试的混合:

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.

Pr>确实,Erlang不能提供定义类型的能力,但是可以考虑一种类型是一种建立在主Erlang类型上的结构,例如,类型<代码>回答< /代码>可以是{,从,时间,列表}的形式,在这种情况下,可以使用模式匹配和主类型测试的混合:

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.

第一种情况可以通过使用带标签的元组和模式匹配来模拟,例如function({typename,Value})->ok。当然,也可以使用记录和is_记录保护。@克里斯:是的,您通常使用标记元组或记录来模拟它。我只是指出没有真正的用户定义类型。第一种情况可以通过使用标记元组和模式匹配来模拟,例如function({typename,Value})->ok。当然,也可以使用记录和is_记录保护。@克里斯:是的,您通常使用标记元组或记录来模拟它。我只是指出,没有真正的用户定义类型。