this question is from a Haskell newbie.
I write code below to check how many True
in a list, and if it has even
number of True
, then return True
, otherwise return `False'.
xor =
foldr xor' False
where
xor' True True = False
xor' False False = False
xor' _ _ = True
However, I found some code snippets below, and it seems that it can do the same thing.. Here is the code:
xor :: [Bool] -> Bool
xor = odd . length . filter id
But I just have no idea how id
works in the above code, could anyone give me some help?
The definition of id
is id x = x
, so filter id
is the same as filter (\x -> x)
. That is it takes all the elements of the list whose value is True
.
The id
function is the identity function, with the very simple definition
id :: a -> a
id x = x
The function filter
has the type
filter :: (a -> Bool) -> [a] -> [a]
It takes a function returning a boolean, applies that function to every element of the list and keeps all the elements for which the function returns True
. So when you have filter id
, it filters the list returning all the elements equal to True
.
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