OriginalUtter
OriginalUtter

Reputation: 669

Possible to match argument by type in Erlang?

I'm wondering if it's possible to have a function that does different things for different argument types, including user-defined type.

This is an example of what I want to do:

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

Is this possible and if it is, what is the syntax for doing this?

Upvotes: 0

Views: 442

Answers (2)

rvirding
rvirding

Reputation: 20916

You cannot define your own datatypes in Erlang so the first clause is impossible. You do type testing in the guard so the 2nd would become:

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

What can do in the guard is very restricted and it consists of simple tests, for example type tests. Read about Guard Sequences.

Upvotes: 2

Pascal
Pascal

Reputation: 14042

It is true that erlang does not offer the ability to define types, but one can consider that a type may be a structure built on primary erlang types for example a type answer could be of the form {From,Time,List} and in this case it is possible to use a mix of pattern matching and primary type test:

myfunction({From,Time,List}) when is_pid(From), is_integer(Time), Time >= 0, is_list(List) ->
    dothis;
myfunction(I) when is_integer(I) ->
    dothat.

and to be closer than the simple type test you are looking for, you can use a macro for testing

-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.   

or even

-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.

Upvotes: 4

Related Questions