What is the use of identity function? It simply returns the same value. Hence, instead of putting (identity x)
, why not simply put x
? Could someone give some examples of using identity function in Racket/Scheme? There are no examples on these documentation page: https://docs.racket-lang.org/htdp-langs/beginner.html#%28def.htdp-beginner.%28%28lib._lang%2Fhtdp-beginner..rkt%29.identity%29%29 and https://docs.racket-lang.org/reference/procedures.html?q=identity#%28def.%28%28lib._racket%2Ffunction..rkt%29._identity%29%29

- 23,686
- 25
- 112
- 234
-
There a few related questions about using the identity function in other languages, the idea is probably the same, see for example http://stackoverflow.com/questions/3136338/uses-for-haskell-id-function or http://stackoverflow.com/questions/15421502/is-there-any-good-example-of-use-cases-for-angular-identity?noredirect=1&lq=1 – Thilo Aug 20 '16 at 06:34
-
Same could be asked about constant functions ;). – Alexey Feb 05 '18 at 16:07
1 Answers
The identity
function is mostly useful as an argument to certain higher-order functions (functions which take functions as arguments) when a function performs a certain sort of mapping customized by its argument, and you wish to pass the value through unchanged.†
One extremely common idiom in Scheme/Racket is using (filter identity ...)
to remove all #f
values from a list:
> (filter identity '(1 2 #f 4))
'(1 2 4)
This works because filter
applies the provided function to each of the elements of a list, then discards values that result in #f
. By using identity
, the values themselves are checked. In this sense, identity
is the functional “no-op”.
You may sometimes see this idiom spelled (filter values ...)
instead of (filter identity ...)
because values
happens to be the identity function when provided with one argument, and it comes from racket/base
instead of racket/function
. I prefer the version that uses identity
explicitly, though, because I think it is a little bit clearer what’s going on.
† This description of the identity function comes from this nice answer for the Haskell equivalent question.

- 1
- 1

- 43,109
- 15
- 131
- 205
-
1
-
-
@X10D If you want to pass a function always returning false you can do (lambda (x) #f) – Paul Stelian Apr 01 '18 at 10:45