Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the definition of null function in Haskell Prelude so strange?

The definition of null function in Prelude is the following:

null             :: [a] -> Bool
null []          =  True
null (_:_)       =  False

What confused me is the third line of the definition, why does it write:

null(_:_)        = False

Instead of:

null any = False

Does it have anything to do with the compiler optimization?

like image 759
Leonard Ge Avatar asked Oct 11 '17 15:10

Leonard Ge


1 Answers

Does it have anything to do with the compiler optimization?

No, in fact one can say that writing null (_:_) is less efficient than null any (in case the compiler does not optimizes this), since now you ask Haskell to verify that it is indeed the "cons". Although if a compiler does some bookkeeping on data types, it is of course easy to optimize this away. As far as I know, most compilers like ghc and almost all compilers not written by three year old kids indeed will do this.

First of all it is better not to write a wilcard _ (or name it any) since the definition of a list (and any other datatype might change). Although for a list the odds are very unlikely, it could be possible that someone redefines a list. For instance like:

data [a] = [] | (a:[a]) | (Int///[a])

where for instance the latter pattern means that the list is repeated a number of times. In that case, a compiler not written by a three year old kid :) will warn that about incomplete patterns for null: it will thus claim that the (_///_) pattern was not specified. Whereas if you use a wildcard, it will fallback to the null any case.

In general one better uses wildcards with care: only in case you really do not care about what is given to the function, you should use wildcards.

like image 90
Willem Van Onsem Avatar answered Sep 26 '22 15:09

Willem Van Onsem