Leonard Ge
Leonard Ge

Reputation: 879

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?

Upvotes: 6

Views: 358

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477190

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.

Upvotes: 5

Related Questions