Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
76 views
in Technique[技术] by (71.8m points)

Order of code in Clojure

I have a simple yet frustrating problem in Clojure, I have a function (let's call it read-function) which figures out what the user wants to do from his input then calls another function that does that (let's call it action-function). This action-function calls the read-function when it's done so the user can perform another task.

Now my problem is that if I put the code for read-function before the code for action-function, I get an error in read-function saying that it doesn't know what action-function is (because the code for it is further down) and if I do the opposite, well I get a similar error obviously, saying that read-function cannot be resolved etc.

Is there a simple way to fix this ?

The actual code:

(defn ajout [botin]
  (def botin botin)
  (readCmd botin)
)

(defn readCmd [botin]
  (println "Entrez une commande svp ")
  (def botin botin)
  (let [cmd (read-line)]
    (if (.equals cmd "a") ((println "Ajout 8o") (ajout botin))
      (if (.equals cmd "e") ((println "Elim 8o") (eliminer botin))
        (if (.equals cmd "i") ((println "Imprim 8o") (imprimer botin))
          ((println "Commande invalide, nous vous rapellons que les commandes possibles sont : ") (print-les-cmd) (readCmd))))))


)

like this, I get an error at the (readCmd botin) line in the ajout function saying : Unable to resolve symbol: readCmd in this context

If I put the code for these two functions in the reverse order I will get an error saying : Unable to resolve symbol: ajout in this context

question from:https://stackoverflow.com/questions/1116831/order-of-code-in-clojure

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use forward declarations in Clojure so you can call functions that haven't been defined yet.

(declare readCmd)

should work!

In Clojure, the order in which you define functions is important, a function can't call another function (or anything for that matter) that hasn't been defined yet. That's why we have forward declarations.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...