pandoragami
pandoragami

Reputation: 5575

Multiple matches within receive..end for finding case..of?

I'm having trouble compiling the following code,

2> c(match).
match.erl:13: syntax error before: '{'
match.erl:2: function receiver/0 undefined
error

match.erl

-module(match).
-export([receiver/0]).

receiver() ->
    receive
        {From, A, B} ->
            case A =:= B of
                true ->
                    From ! "true";
                false ->
                    From ! "false"
            end
        {From, A, B, C}->
            case A =:= B =:= C of
                true ->
                    From ! "true";
                false ->
                    From ! "false"
            end
    end.

I've tried doing every possible semicolon, period, comma before the match {From, A, B, C}-> and nothing seems to work. This is where Erlangs' syntax is a nightmare!

Upvotes: 0

Views: 272

Answers (2)

Pascal
Pascal

Reputation: 14042

Please, use pattern matching

-module(match).
-export([receiver/0]).

receiver() ->
    receive
        {From, A, A} ->
                    From ! "true";
        {From, _, _} ->
                    From ! "false";
        {From, A, A, A}->
                    From ! "true";
        {From, _, _, _}->
                    From ! "false"
    end.

or guards

-module(match).
-export([receiver/0]).

receiver() ->
    receive
        {From, A, B} when A =:= B ->
                    From ! "true";
        {From, _, _} ->
                    From ! "false";
        {From, A, B, C} when A =:= B andalso A =:= C ->
                    From ! "true";
        {From, _, _, _}->
                    From ! "false"
    end.

or boolean operator

-module(match).
-export([receiver/0]).

    receiver() ->
        receive
            {From, A, B} ->
                case A =:= B of
                    true ->
                        From ! "true";
                    false ->
                        From ! "false"
                end;
            {From, A, B, C}->
                case A =:= B andalso A =:= C of
                    true ->
                        From ! "true";
                    false ->
                        From ! "false"
                end
        end.

Upvotes: 5

lmsteffan
lmsteffan

Reputation: 870

I believe that it's not possible to compare three values like you try to do in 'A =:= B =:= C'. Comparing only two of them makes your code compilable.

Upvotes: 2

Related Questions