Of what use is identity function in Racket?
Asked Answered
C

1

5

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

Cas answered 20/8, 2016 at 6:30 Comment(2)
There a few related questions about using the identity function in other languages, the idea is probably the same, see for example #3136838 or #15422002Catalog
Same could be asked about constant functions ;).Lions
C
11

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.

Corcoran answered 20/8, 2016 at 6:38 Comment(3)
is there anyway to pass #f instead the idenity function?Boast
@Boast No, there isn’t. Why would you want to do that?Corcoran
@Boast If you want to pass a function always returning false you can do (lambda (x) #f)Tumefy

© 2022 - 2024 — McMap. All rights reserved.