Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is "when" used in this function?

There is this index function in "Erlang Programming":

index(0, [X|_]) -> X;
index(N, [_|Xs]) when N>0 -> index(N-1, Xs)

Isn't the guard "when N>0" superfluous because of the pattern matching? Calling index(0, List) will never end up in the second clause so N will always be > 0. Or am I totally wrong here?

like image 458
Jan Deinhard Avatar asked Aug 08 '10 14:08

Jan Deinhard


People also ask

What is the use of when?

We use when to refer to a future situation or condition that we are certain of, whereas we use if to introduce a possible or unreal situation. When I see Gary, I'll tell him that you said hello. I will definitely see Gary. If I see Gary, I'll tell him that you said hello.

What tense do we use with when?

Use “when” in a clause with a single action, using a simple past or present tense.

Is when an adverb?

The word “when” has multiple functions. It can be used as an adverb, conjunction, pronoun, and noun. This word is categorized as an adverb because it modifies a verb, and adjective, or another adverb by indicating the time.

Why do we use that clause?

We use a noun + that-clause to express opinions and feelings, often about certainty and possibility. We also use that with reporting nouns.


1 Answers

The function works correctly for N>=0. Without a guard, for N<0 it would traverse the whole list:

index(-2,[1,2,3]) -> index(-3,[2,3]) -> ... -> index(-5,[]) -> error.

That isn't a large problem, only you might get a confusing exception. In languages with infinite lists (Haskell, Ocaml), forgetting about that guard might lead to infinite loop: index(-1, [0,0,0..]).

like image 129
sdcvvc Avatar answered Oct 01 '22 19:10

sdcvvc