简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM