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!
Get Programming with HaskellYou can't return an empty list, because an empty list is the same type as the elements of the list.
(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 ).
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.
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
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. [[]]
.
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