Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wishful thinking in Clojure

In Scheme I was used to do something like this

(define (f x) (g x))
(define (g x) (+ x 42))
(g 0)

That is, I was used to define functions in terms of other momentaneously unbounded functions. Why isn't this possible in Clojure? For example on a Clojure REPL the following isn't valid

(defn f [x] (g x))
(defn g [x] (+ x 42))
(g 0)
like image 547
Matteo Avatar asked Dec 18 '22 17:12

Matteo


1 Answers

the thing is every line is being compiled in repl, so there is no g function when f is being compiled. You should add (declare g) before (defn f... so the compiler would be aware of this function:

user> (declare g)
#'user/g

user> (defn f [x] (g x))
#'user/f

user> (defn g [x] (+ x 42))
#'user/g

user> (g 0)
42
like image 114
leetwinski Avatar answered Jan 09 '23 18:01

leetwinski