listhaskellbooleannon-exhaustive-patterns

Toggle every element in a list in haskell


I have to write a function that toggles a list of given Booleans for example :

input : toggle [True,False,False]

output: [False,True,True]

This is what I came up with

toggle :: [Bool] -> [Bool]
toggle [a] = not a:[a]
toggle [] = []

And I keep getting this error:

*** Exception: Uebung3.hs:38:1-20: Non-exhaustive patterns in function toggle

It's a very basic question, I come from Java and have just started to learn Haskell.


Solution

  • As a pattern, [a] is a singleton list: a list containing just one element, a.

    As a type, [a] is a list of a-type values. But not as a pattern.

    The pattern (a : as) stands for a non-empty list with head element a and the rest of elements as. Use it as the pattern in your equation:

    -- toggle [a] = not a:[a]
    toggle (a : as) = not a : _______ as
    toggle [] = []
    

    You need to complete it by filling in the blanks, to make this definition recursive.

    Definitions are recursive when they refer to self to make a helper call to continue doing their job for the remaining part of their input.

    The patterns [] (empty list) and (a : as) (non-empty list) are mutually exclusive. More, together they are exhaustive: there are no other possibilities for a list value to be.

    But the patterns [] and [a] together are not exhaustive: they do not cover the case of lists of two elements, or longer. The [a] pattern is the same as (a : []), a list with an empty list as its tail.