Head and tail call to empty list bringing exception

I follow the tutorial. (Real World Haskell)

And I have one initial question about the head and tail caused by the empty list: in GHCi it returns an exception.

Intuitively, I think I would say that both of them should return an empty list. Could you fix me? Why not? (as far as I remember, in OzML to the left or to the right of the empty list nil is returned)

Of course, I have not yet touched on this topic in the textbook, but is this not a source of errors (if no arguments are indicated)? I mean, if you ever go to a function list of arguments that can be optionnal, reading them with your head could lead to an error?

I just know the behavior of GHCi, I don’t know what happens when compiling.

+3
source share
1 answer

Intuitively, I think both of them should return an empty list. Could you fix me? Why not?

Good - head- [a] -> a. It returns a single, first element; no list.

And when the first list is not in the empty list? Well, what to return? You cannot create a type value afrom nothing, so all that remains undefinedis an error.


And tail? A tail is basically a list without its first element - i.e. One element is shorter than the original. You cannot defend these laws when there is no first element.

, ( , tail [] == []). undefined.


:

, , , ? , - , optionnal, ?

, , , . , , . : * / ** - .

sum     [] = 0
sum (x:xs) = x + sum xs

, , , .

+13

Source: https://habr.com/ru/post/1761013/


All Articles