clojurecompojure-api

How do I make a literal function that takes no args and return a constant value?


I'm trying to learn Clojure, and am blocked up around the literal function syntax. I can't figure out what the literal function equivalent of (defn fourteen [] 14) is.

(def fourteen (fn [] 14))
;; => #'user/fourteen
(fourteen)
;; => 14
(defn defn-fourteen [] 14)
;; => #'user/defn-fourteen
(defn-fourteen)
;; => 14
(def literal-14 #(14))
;; => #'user/literal-14
(literal-14)
;; ClassCastException java.lang.Long cannot be cast to clojure.lang.IFn  user/literal-14 (form-init2956929406616221071.clj:1)

I don't think this is a dup of How many arguments does an anonymous function expect in clojure?, but maybe it is and I just don't possess the experience to recognize that.

How, or can, I def literal-14 to allow the (literal-14) invocation to work?


Solution

  • 14 isn't a function, but do or -> will do in a pinch:

    #(do 14)
    #(-> 14)