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?
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.
Use “when” in a clause with a single action, using a simple past or present tense.
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.
We use a noun + that-clause to express opinions and feelings, often about certainty and possibility. We also use that with reporting nouns.
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..]).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With