Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does "id" in this Haskell code mean?

Tags:

haskell

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?

like image 762
lllllllllllll Avatar asked Jun 06 '15 15:06

lllllllllllll


2 Answers

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.

like image 76
sepp2k Avatar answered Nov 01 '22 14:11

sepp2k


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.

like image 11
bheklilr Avatar answered Nov 01 '22 14:11

bheklilr