lobsterism
lobsterism

Reputation: 3509

Working with long let expressions in Clojure REPL

I run into this scenario pretty often and was wondering if there's an easy solution. Say I've got a Clojure source file that has a let expression like the following:

(let [a (...)
      b (...)
      c (...)
      d (...)
      e (...)
      f (...)
      g (...)
      h (...)] 
  (...))

where each value is dependent on some of the values above.

Then when I want to manually work with say the expression that defines h in the REPL (assume that at least one of the inputs is some huge map JSON response or something that would be even more of a pain to type out manually), then I find myself manually doing

(def a (...))
(def b (...))
(def c (...))
(def d (...))
(def e (...))
(def f (...))
(def g (...))

before I can even start trying to mess with h.

So usually that means typing (def ) into the REPL, then moving my mouse, copy the a (...) from the let expression, pasting back into the (def ) then hitting enter, and then going back and doing the same thing for b and so on.

Is there a quicker way to go about this?

Upvotes: 1

Views: 321

Answers (2)

d.j.sheldrick
d.j.sheldrick

Reputation: 1591

You could also write a macro which takes the bindings of a let form and turns it into a sequence of def forms.

(defmacro letdef [bindings]
  (apply list `do (for [[s expr] (partition-all 2 bindings)]
                    `(def ~s ~expr))))

(letdef [a 1
         b 2
         c 3
         etc (+ a b c)])

(println etc) ;=> 6

Upvotes: 3

overthink
overthink

Reputation: 24443

Here's a hack that might work for you:

(let [a (...)
      b (...)
      c (...)
      d (...)
      e (...)
      f (...)
      g (...)
      h (...)
      _ (def h' h)] 
  (...))

Obviously you'd never want something like this is checked in code, but for hacking things in the REPL it might suffice.

Upvotes: 1

Related Questions