Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Haskell let me return an empty list where a list inside a list is expected?

I'm really new to Haskell and have been going through the 99 problems translation. This is my solution to number 9:

pack :: (Eq a) => [a] -> [[a]]
pack (xs)
    | null xs = []
    | otherwise = 
        let (matched, unmatched) = span (== head xs) xs
        in [matched] ++ pack unmatched

I don't get how I'm allowed to do | null xs = [] when the type signature says the function returns a [[]]. I've seen other solutions to the same problem do the same thing.

I mean, I'm not complaining, but is this something specifically allowed? Are there any caveats I have to look out for?

I'm using the GHCi on a default Windows 7 Haskell Platform 2013.2.0.0 installation, if that helps.

like image 887
user1834037 Avatar asked Aug 25 '13 18:08

user1834037


People also ask

How do I return an empty list in Haskell?

Get Programming with HaskellYou can't return an empty list, because an empty list is the same type as the elements of the list.

How do lists work in Haskell?

In Haskell, lists are a homogenous data structure. It stores several elements of the same type. That means that we can have a list of integers or a list of characters but we can't have a list that has a few integers and then a few characters.

How do you check if a list contains an element Haskell?

elem :: element -> list -> Bool. Use elem if you want to check whether a given element exists within a list.


1 Answers

[] is an empty list. It has the following type:

[] :: [b] -- Note: I'm using b instead of a because your function already uses a

That b can be everything. Can you choose a b such that [b] ~ [[a]]? (~ is equality for types)? Yes, just use b ~ [a] and the type of [] becomes:

[] :: [b] :: [[a]]     -- When b ~ [a]

So [] is also a value of type [[a]]. [] is a valid value for any type of list, be it a list of a's or a list of lists of a's.

like image 137
bennofs Avatar answered Sep 22 '22 06:09

bennofs