This is useful as an argument for higher order functions (functions that take functions as arguments), where you want a particular value to remain unchanged.
Example 1 Leave the value alone if it is in order, otherwise return the default value of 7.
Prelude Data.Maybe> :t maybe maybe :: b -> (a -> b) -> Maybe a -> b Prelude Data.Maybe> maybe 7 id (Just 2) 2
Example 2 : creating a function through a fold:
Prelude Data.Maybe> :t foldr (.) id [(+2), (*7)] :: (Num a) => a -> a Prelude Data.Maybe> let f = foldr (.) id [(+2), (*7)] Prelude Data.Maybe> f 7 51
We built a new function f , folding the list of functions together with (.) , Using id as the base case.
Example 3 : the basic case for functions as monoids (simplified).
instance Monoid (a -> a) where mempty = id f `mappend` g = (f . g)
Like our bend example, functions can be viewed as concatenated values, with id serving as an empty case and (.) Serving as an append.
Example 4 : a trivial hash function.
Data.HashTable> h <- new (==) id :: IO (HashTable Data.Int.Int32 Int) Data.HashTable> insert h 7 2 Data.HashTable> Data.HashTable.lookup h 7 Just 2
Hashtables require hashing. But what if your key is already hashed? Then pass the id function to fill as your hash method, with zero overhead.
Don Stewart Jun 28 '10 at 21:45 2010-06-28 21:45
source share