Huang_Hai_Feng
Huang_Hai_Feng

Reputation: 287

pattern matching for tuple in erlang

I'm a new learner of erlang, and i'm looking for a book called Introducing erlang. In the book, it has some examples as below:

-module(ask).
-export([term/0]).

term() ->
    Input = io:read("What {planemo, distance} ? >>"),
    process_term(Input).

process_term({ok, Term}) when is_tuple(Term) ->
    Velocity = drop:fall_velocity(Term),
    io:format("Yields ~w. ~n",[Velocity]),
    term();

process_term({ok, quit}) ->
    io:format("Goodbye.~n");
    % does not call term() again

process_term({ok, _}) ->
    io:format("You must enter a tuple.~n"),
    term();

process_term({error, _}) ->
    io:format("You must enter a tuple with correct syntax.~n"),
    term().

Below is the examples which call the ask module:

6> c(ask).
{ok,ask}
7> ask:term().
What {planet, distance} ? >>{mars,20}.
Yields 12.181953866272849.
What {planet, distance} ? >>20.
You must enter a tuple.
What {planet, distance} ? >>quit.
Goodbye.
ok

I don't understand why What {planet, distance} ? >>quit. matches the process_term({ok, quit}) function? you entered only 'quit', not a tuple, I think it should not match process_term({ok, quit}) function. Could anybody out there explain why?

Upvotes: 0

Views: 1653

Answers (2)

liam_g
liam_g

Reputation: 311

Also, In your code, you have process_term({ok, Term}) when is_tuple(Term) -> which takes the input, provided it is a tuple, hence the when clause. When you enter 'quit', it does not have to be a tuple to be accepted by the {ok, quit}, it pattern matches them and returns the ouput. Hope this helps.

Upvotes: 0

emvee
emvee

Reputation: 4449

According to the documentation of io:read/1 (http://www.erlang.org/doc/man/io.html#read-1) it returns a tuple {ok, Term}. Ie you type foo, io:read returns {ok, foo}, you type {bar, 10}, io:read returns {ok, {bar, 10}}.

All the process_term clauses match on {ok, _whatever the user typed_}, or if something failed, {error, Reason} (which is all Erlang style).

Upvotes: 4

Related Questions