1

I am trying to convert heavily nested expressions in Clojure. One example is the following:

(distinct (flatten (map keys (flatten (filter vector? (vals data))))))

The threaded form would be:

(->> data vals (filter vector?) flatten (map keys) flatten distinct)

Is it possible in Clojure to create a function or macro that help me automate getting the threaded form with the nested form as input? Or are there any third-party tools that I can use?

5
  • I can't think of any use case for such a macro; could you give an example? Or are you asking for a way to do this in your source code with an editor? Commented Apr 3, 2016 at 13:02
  • @Elogent Yes. I guess it's use case is the developer's own convenience in refactoring heavily nested code. Commented Apr 3, 2016 at 13:14
  • 1
    The only reason one would write a macro that converts from a nested form to a threaded form would be so that they could write the nested form in their source code and have Clojure convert it to the threaded form in the macroexpansion phase. Such a macro would be completely useless, because the threading macros just convert right back to the nested form. Commented Apr 3, 2016 at 13:24
  • True, since they are the same in terms of execution. However, it would be useful to know how to do it in terms of string manipulation. Commented Apr 3, 2016 at 13:40
  • Note that I am also asking for third-party tools. Commented Apr 3, 2016 at 13:44

2 Answers 2

5

If you're using CIDER, I would recommend clj-refactor. It has refactoring capability for both -> and ->>, as well as a whole bunch of other stuff.

Sign up to request clarification or add additional context in comments.

1 Comment

Lighttable also has a plugin which will do this: github.com/rundis/clj-light-refactor#threading
0

Further tooling support:

IntelliJ - Cursive plugin: Since version 0.1.29 provides:

New Structural Editing commands: Kill Sexp, Thread/Unthread Form, Move Form Up/Down.


VS Code - Calva plugin: You would use the Thread Last All command to get the desired result. Full list of threading options are:

Command Title Command Key
Thread First clojureLsp.refactor.threadFirst
Thread First All clojureLsp.refactor.threadFirstAll
Thread Last clojureLsp.refactor.threadLast
Thread Last All clojureLsp.refactor.threadLastAll

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.