Does the identity function in Clojure have the same usage and purpose as the id function in Haskell?
Asked Answered
P

1

8

In Clojure we have the identity function. It is used as follows:

user=> (filter identity [1 2 3 nil 4 false true 1234])
(1 2 3 4 true 1234)

user=> (partition-by identity (sort "abcdaabccc"))
((\a \a \a) (\b \b) (\c \c \c \c) (\d))

From what I can see in Haskell - id is used when using lenses and is used in other higher order functions.

My question is (apart from the obvious Type system differences) Does the identity function in Clojure have the same usage and purpose as the id function in Haskell?

Why I ask is when I look at the following example of a Lens in Clojure - we see Id defined in terms of functor:

(defprotocol Functor
    (fmap [functor f] "fmap :: f a -> (a -> b) -> f b"))

;; data Id a = Id { runId :: a }
(defrecord Id [runId]
    Functor
   (fmap [functor f]
        (Id. (f (:runId functor)))))

So I feel like I'm missing something.

Prewitt answered 28/9, 2014 at 11:37 Comment(1)
The definition of Id in clojure equals the Identity functor in Haskell.Engrain
C
8

The id function in Haskell is the I combinator of lambda calculus. It is the trival function:

-- | Identity function.
id :: a -> a
id x = x

It is useful the way that 0 or the empty list are useful.

The identity function in Clojure is equivalent in that it returns its argument unmodified.

(defn identity
  "Returns its argument."
  {:added "1.0"
   :static true}
  [x] x)

Other notions of e.g Identity monads and so forth are not directly connected to the id function.

Cohleen answered 28/9, 2014 at 11:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.