0

I'm a beginner in clojure. Could you help with the last 2 expression? I cannot figure out why "Unable to resolve symbol: result in this context". Thanks a lot! (I'm trying to solve a problem in which there are references within list.)

(let [result ['(get result 1) 2]]
  (println (get result 1))          ;this can work
  (println (eval '(get result 1)))  ;error
  (println (eval(first result))))   ;error`

I expect (map eval result) to yield [2 2].

Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
ppppc
  • 1

1 Answers1

0

eval evaluates the forms you send it in the namespace bound to *ns* but with a blank lexical scope. So surrounding let values are not carried over. Defined vars, dynamic bindings etc however will be there. This post explains it well Variable scope + eval in Clojure

As an aside, eval is pretty powerful and confusing liquor to be sipping on as a beginner. In 6-7 years of programming in clojure I have never needed it.

bfabry
  • 1,874
  • 1
  • 13
  • 21
  • Hi tks for your help! Is there a better way to deal with this : [(+ 1 2nd) 0 (- 1st 3) (* 3rd 1st)] (nth means a nth element inside the vec) – ppppc Oct 31 '19 at 23:02
  • I believe you are looking for general advice, which SO is not well suited for. My recommendation would be the #beginner channel on the clojurians slack for such advice – bfabry Oct 31 '19 at 23:07
  • 1
    eval does not start with a blank namespace. it evals in the contect of the namespace where eval was invoked – Arthur Ulfeldt Oct 31 '19 at 23:07
  • 1
    You are correct, it starts with a blank lexical scope. Thank you – bfabry Oct 31 '19 at 23:08
  • 1
    one way to explain it is, as if the expression had been typed into the file as a top level form. – Arthur Ulfeldt Oct 31 '19 at 23:09
  • 1
    @ArthurUlfeldt Not quite that, either. It evals in the context of `*ns*`. In an interactive repl, this is the namespace you are defining, but in the context of a non-interactive program `*ns*` is usually, I think, `user`. You can see this by running a program like `(def x 1) (defn -main [] (println (eval '*ns*)) (println (eval 'x)))` – amalloy Oct 31 '19 at 23:32