a head' xs = case xs...">

What does (x: _) and [x: _] mean?

head' :: [a] -> a head' [] = error "No head for empty lists!" head' (x:_) = x head' :: [a] -> a head' xs = case xs of [] -> error "No head for empty lists!" (x:_) -> x 

I am asking a fairly simple question that I do not understand. In the above code, I see that it accepts a list for input. But the third line says (x:_) that confuses me. Can someone explain to me why they wrote (x:_) instead of [x:_] ?

And plus, I don't understand what (x:_) means.

Thanks.

+4
source share
2 answers

: is a constructor for lists, which translates the head into the new list as its left argument, and the tail into its right argument. If you use it as a template, as here, this means that the head of the list that you are matching is given to the left drawing and the tail to the right.

So, in this case, the head of the list is stored in the variable x , and the tail is not used ( _ means that you do not care about the value).

And yes, you can also use [] to map patterns to lists, but only lists of a fixed size. For example, the template [x] corresponds to a list with exactly one element, which is then stored in the variable x . Similarly, [x,y] will correspond to a list with two elements.

Your proposed template [x:y] will thus correspond to a list with one element that matches the x:y template. In other words, it will correspond to a list of lists that contains exactly one list.

+14
source

This is a concept called pattern matching . : is an infix constructor, just as + is an infix function. In Haskell, the pattern matches the constructors.

 (1 : 2 : 3 : []) 

Same as [1, 2, 3] , the square bracket designation is just syntactic sugar for creating lists.

Your template (x : _) means that you want to bind the first element of the list to x and that you don't care, the rest of the list is _ .

+5
source

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


All Articles