Search code examples
lambdaclojurefunctional-programmingfunctor

How could a c++ "function object" (functor) be defined in Clojure?


By "c++ function object" (functor) I mean: "an object for which the function call operator is defined."

I guess there are several ways to do this. Just for instance, let's say we need a parameterized function:

f(x) = sin(x*freq) // maths

We could use "a function constructor":

(defn newSinus [freq] 
  (fn [x] (Math/sin (* freq x)))
)

(def sin1 (newSinus 2.0) )
(def sin2 (newSinus 1.5) )

(println (sin1 1.5))
(println (sin2 2.0))

But, what if we want to read the parameter in sin1 or sin2?

How many ways we can do it?

Thanks.


Solution

  • I'm not sure exactly what you're asking, but you can define a record that's callable as a function by satisfying the clojure.lang.IFn interface:

    (defrecord Adder [x]
      clojure.lang.IFn
      (invoke [_ y]
        (+ x y)))
    
    ((->Adder 3) 4) ; => 7