Why is the when used in this function?
This index function is in the "Erlang Program":
index(0, [X|_]) -> X; index(N, [_|Xs]) when N>0 -> index(N-1, Xs) Is the "at N> 0" protection unnecessary due to template matching? The calling index (0, List) will never appear in the second sentence, so N will always be> 0. Or am I completely wrong here?
The function works correctly when N> = 0. Without protection, for N <0 it will move throughout the list:
index (-2, [1,2,3]) β index (-3, [2,3]) β ... β index (-5, []) β error.
This is not a big problem, only you can get a confusing exception. In languages ββwith infinite lists (Haskell, Ocaml), forgetting that the guard can lead to an infinite loop: index (-1, [0,0,0 ..]).
The if clause protects against negative indices (edit: see comments on the original question;).
It also gives clearer code, as you explicitly say, when this sentence is valid, and not just the default. Yes, I know that in some (many) cases this cannot be done properly, as the test can become very complicated or that you want to get some default case. But not here.