Tilman Zuckmantel
Tilman Zuckmantel

Reputation: 720

Patternmatching for empty List in Haskell

as i am new to Haskell i am not quite familiar with everything. i tried to implement a function using pattern matching but this wont work as it gives the following Exception: Prelude.head empty list. This is the code sample:

swapListToTowers::[[Bool]]->[[Bool]]
swapListToTowers [] = []
swapListToTowers xs = [head x| x <-xs]:swapListToTowers (cutOfFirstElements xs)


cutOfFirstElements::[[Bool]]->[[Bool]]
cutOfFirstElements [] = []
cutOfFirstElements xs = [tail x | x <- xs]

I think the case for capturing the empty list does not quite work , does it? Thanks in advance for any help!

Upvotes: 7

Views: 4251

Answers (2)

Hamish
Hamish

Reputation: 1015

I think you're missing a pattern to match your inner list, so when you get to your list comprehension, there hasn't been a check to see if your inner list is empty

I'm not sure what your function is designed to do, but you might want to split out your functions a bit like this so you can deal with the empty sublist on it's own

swapListToTowers::[[Bool]]->[[Bool]]
swapListToTowers [] = []
swapListToTowers xs = swapListToTowersInner (head xs) : ...

swapListToTowersInner :: [Bool] -> [Bool]
swapListToTowersInner [] = []
swapListToTowersInner xs = head xs

... similarly here for cutOfFirstElements

Upvotes: 5

Mark Seemann
Mark Seemann

Reputation: 233150

Both functions take as arguments list of lists. The empty list match [] only matches the outer list, but not the case where the outer list is non-empty, but the inner list isn't; e.g. [[]].

Upvotes: 3

Related Questions