Redefining a let'd variable in Clojure loop

后端 未结 4 1406
难免孤独
难免孤独 2021-02-01 02:00

OK. I\'ve been tinkering with Clojure and I continually run into the same problem. Let\'s take this little fragment of code:

(let [x 128]
  (while (> x 1)
            


        
4条回答
  •  没有蜡笔的小新
    2021-02-01 03:03

    Vars (that's what you get when you "def" something) aren't meant to be reassigned (but can be):

    user=> (def k 1)
    #'user/k
    user=> k
    1
    

    There's nothing stopping you from doing:

    user=> (def k 2)
    #'user/k
    user=> k
    2
    

    If you want a thread-local settable "place" you can use "binding" and "set!":

    user=> (def j) ; this var is still unbound (no value)
    #'user/j
    user=> j
    java.lang.IllegalStateException: Var user/j is unbound. (NO_SOURCE_FILE:0)
    user=> (binding [j 0] j)
    0
    

    So then you can write a loop like this:

    user=> (binding [j 0]
             (while (< j 10)
               (println j)
               (set! j (inc j))))
    0
    1
    2
    3
    4
    5
    6
    7
    8
    9
    nil
    

    But I think this is pretty unidiomatic.

提交回复
热议问题