简体   繁体   中英

Of what use is identity function in Racket?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM