Consider this silly example: imagine you had an operation that fetches
stuff from a resource (DB, network, etc.) and that upon failing it
returns nil. Additionally, imagine that you're interested in running
this operation for several resources and keeping those values which
didn't fail. You can do so with identity:
user=> (defn my-operation-that-might-fail [x]
(if (= x "foo") x nil))
#'user/my-operation-that-might-fail
user=> (def some-values ["bar" "foo" "baz"])
#'user/some-values
user=> (filter identity (map your-pred some-values))
("foo")
user=>
and you have your single operation that didn't fail.
My 0.5cts.
U
--
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to clo...@googlegroups.com
Note that posts from new members are moderated - please be patient with your first post.
To unsubscribe from this group, send email to
clojure+u...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en
you can also use it to do funny stuff with juxt.
(map (juxt identity f) some-seq)
Sincerely
Meikel
It's most useful when you have functions that take functions as
arguments. For example, I have code that performs a SQL query and then
runs a map-reduce transformation on that. Sometimes, however, I want
just the original data so I can pass in identity (to map) and have it
be a "no-op".
Identity on its own isn't really useful - but in combination with
higher-order functions, it can be very indispensible!
--
Sean A Corfield -- (904) 302-SEAN
An Architect's View -- http://corfield.org/
World Singles, LLC. -- http://worldsingles.com/
Railo Technologies, Inc. -- http://www.getrailo.com/
"Perfection is the enemy of the good."
-- Gustave Flaubert, French realist novelist (1821-1880)
Bingo. An HOF accepts a function that filters/mogrifies data before
processing it in some way. Sometimes, you *don't* want to have that
extra step. There are two ways to do that: one is to have two variants
of the HOF - one which uses the function, and one which doesn't (which
may mean it's not an HOF). The other is identity.
Clojure does both, depending. You can see the first in sort and
sort-by, where sort-by uses a keyfn to extract keys from items in the
collection. You could just identity for the keyfn to sort by items,
but this case is so common it gets it's own function -
sort. Similarly, filter takes a predicate to check which items need to
be removed. If you just want to remove false values, the appropriate
predicate is identity. This case isn't very common, so there's no
second version.
<mike
--
Mike Meyer <m...@mired.org> http://www.mired.org/
Independent Software developer/SCM consultant, email for more information.
O< ascii ribbon campaign - stop html mail - www.asciiribbon.org