0
votes

Can someone post the correct syntax to write a clojure macro that returns a lambda? e.g.

(defmacro x [m]  
   --> returns (fn [m] ...)
2
What should the lambda return? Your example is equivalent to the identity function. - Lee
I decided to delete my answer because Lee is right. On second glance it's not clear what you want. Do you want the function to return the parameter given to the macro, or the parameter given to the function, or name the parameter of the function based on the parameter to the macro? - Carcigenicate
My example clearly requires some clarification - I wasn't quite so interested in the contents of the lambda function as in the correct syntax to generate one from a macro, which confounded me. Apologies for the confusion this generated. - Steve B.
Why is m being used as the macro and the lambda argument, is this a co-incidence? I was going to write an example macro but I couldn't think of anything useful in this construct. - NikoNyrh

2 Answers

0
votes

I believe you want 'constantly'.

Usage: (constantly x) Returns a function that takes any number of arguments and returns x.

0
votes

A macro was requested, although not necessary in this example as this multiply-by-constant-random can be implemented as a normal function as well. Well, this gives you compile-time random constants instead of run-time.

(defmacro multiply-by-constant-random []
  (let [num (Math/random)]
    `(fn [m#] (* m# ~num))))

(macroexpand-1 '(multiply-by-constant-random))
; (clojure.core/fn [m__3184__auto__] (clojure.core/* m__3184__auto__ 0.45643974690448996))

(def f1 (multiply-by-constant-random))
(def f2 (multiply-by-constant-random))
(def f3 (multiply-by-constant-random))

(pprint
  (for [i (range 1 5)]
    (for [f [f1 f2 f3]]
      (f i))))
;((0.30553722493029045 0.9164995864143136 0.22367444865206332)
; (0.6110744498605809  1.8329991728286272 0.44734889730412664)
; (0.9166116747908714  2.749498759242941  0.67102334595619)
; (1.2221488997211618  3.6659983456572545 0.8946977946082533))