Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Patternmatching for empty List in Haskell

Tags:

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!

like image 277
Tilman Zuckmantel Avatar asked Nov 21 '15 12:11

Tilman Zuckmantel


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.

What does Xs do in Haskell?

(x:xs) is a pattern that matches a non-empty list which is formed by something (which gets bound to the x variable) which was cons'd (by the (:) function) onto something else (which gets bound to xs ).

Is empty string Haskell?

A String in Haskell is a list of characters. So to match the empty String you need to match an empty list ( [] ). Your pattern (x:xs) will only match lists or String s with at least one element because it consists of one element ( x ) and the rest ( xs ), which could be empty or non-empty.


2 Answers

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
like image 164
Hamish Avatar answered Nov 01 '22 13:11

Hamish


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. [[]].

like image 43
Mark Seemann Avatar answered Nov 01 '22 11:11

Mark Seemann