Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does this syntax mean in Haskell: ([]:_)

Tags:

haskell

I saw this at a function ([]:_)

Cannot find a definition of it (Google doesn't work well with symbols). So what is it anyway?

type Mat a = [[a]]

myTranspose :: Mat a -> Mat a
myTranspose ([]:_) = []
myTranspose p = (map head p) : myTranspose (map tail p)
like image 678
Joao Parente Avatar asked Jan 13 '18 15:01

Joao Parente


1 Answers

It is pattern matching for a list of lists. It matches with a list with at least one element where the first element is the empty list. For instance [[]], or [[], [2,4]], [[], [], [1,4], [2], [5]].

A list in Haskell is defined as a linked list with two constructors: [], the empty list, and (a:as) the "cons" where a is the "head" (the first element of the list), and as the tail (a list that contains the remaining elements).

Furthermore the underscore _ is used as a "don't care" variable. So it means that we look for a cons pattern (a:as), where a (the first element) is an empty list [], and as is _ so we are not interested in the remaining elements of the list.

In the case of the myTranspose function, it will thus result in an empty list if you give it a list of lists with the first item being an empty list.

like image 185
Willem Van Onsem Avatar answered Oct 22 '22 20:10

Willem Van Onsem