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?
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With