What does "id" mean in this Haskell code?

this question is from Haskell newbies.

I am writing the code below to check the number of True in the list, and if it even has a True number, return True , otherwise return `False '.

 xor = foldr xor' False where xor' True True = False xor' False False = False xor' _ _ = True 

However, I found a few snippets of code below, and it seems that it can do the same. Here is the code:

 xor :: [Bool] -> Bool xor = odd . length . filter id 

But I just donโ€™t know how id works in the above code, can anyone help me?

+6
source share
2 answers

The definition of id is id x = x , so filter id matches filter (\x -> x) . This means that all list items are set to True .

+11
source

The id function is an identity function with a very simple definition

 id :: a -> a id x = x 

The filter function is of type

 filter :: (a -> Bool) -> [a] -> [a] 

It requires a function that returns a boolean, applies this function to each element of the list, and saves all elements for which the function returns True . Therefore, when you have a filter id , it filters a list that returns all elements equal to True .

+8
source

Source: https://habr.com/ru/post/988624/


All Articles