Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getting around lack of "hoisting" in clojure

I have found a few times that I have a group of inter-related functions, and how I would naturally place them in the file ends up conflicting with their dependencies (i.e function 1 depends on function 2, but is above function 1). When I am writing code, I usually keep evaluating top level expressions, and will only evaluate the whole file to refresh dependencies on refs or whatnot. I am finding that quite frequently, I end up with a dependency conflict, and end up having to juggle a bunch of functions around.

In other languages I know, as soon as you declare a function, it gets "hoisted" behind the scenes as if it appeared before anything else. That way you dont need to worry about the order of things in your code, and can treat functions as modular bits of code. It is the lack of this feature that keeps biting me in clojure. Am I doing something wrong? Its more a minor annoyance then a huge deal, is this something you just sort of get used to paying attention to?

like image 502
Matt Briggs Avatar asked Mar 30 '11 18:03

Matt Briggs


1 Answers

declare solves this problem nicely

declare
macro
Usage: (declare & names)
defs the supplied var names with no bindings, useful for making forward declarations.
Added in Clojure version 1.0

you can avoid juggling the function order by adding a declare statement to the start of your namespace

(declare fun1 fun2 fun3)

(defn fun3 [] (fun1))
(defn fun1 [] (fun2))
(defn fun2 [] 42)
like image 178
Arthur Ulfeldt Avatar answered Nov 18 '22 01:11

Arthur Ulfeldt