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.
Get Programming with HaskellYou can't return an empty list, because an empty list is the same type as the elements of the list.
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.
elem :: element -> list -> Bool. Use elem if you want to check whether a given element exists within a list.
[]
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With