Convert to cycle ... recur recursion

As I understand it, recursion in Clojure is without using a loop. Repeated syntax may not be a problem for short sequences. However, using the loop .. recur syntax is the preferred method for writing recursive functions. So, I would like to start with the preferred method.

However, I struggled to convert this function [edit], which returns the skeleton of the sequence (structure of the sequence without its values)

(defn skl [tree] (map skl (filter seq? tree))) 

with this data

 (def test_data1 '(1 (2 3) ( ) (( )) :a)) (def test_data2 '(1 2 (3 4) (5 ( 6 7 8)))) 

to loop .. recur syntax. Any ideas or pointers to examples would be appreciated.

+6
source share
3 answers

You might want to look into the zipper library, which allows you to structure your tree editing well, although it will probably be less elegant than your original. I almost never need to use a loop ... recur. There is almost always a higher order function that solves the problem more efficiently with the same or better efficiency.

Replacing map with loop ... recur makes the code more verbose and less comprehensible. You also lose the benefits of alternating sequences.

+3
source

Loop and recur are transformations of simple iteration. However, the descent into the tree is inherently recursive. You will need to maintain the stack manually in order to convert it to a single iteration. Thus, there is no “simple” conversion for your code.

+4
source

Take a look at clojure.walk source. This is a library for performing (bulk) operations in all Clojure nested data structures (excluding ordered maps). There is a very powerful, but deceptively simple kind of code, using recursion through locally defined anonymous functions, without using loop / recur.

Most of the functions there are based on the postwalk and prewalk functions, which in turn are based on the walk function. With the source text and the (prewalk-demo form) and (postwalk-demo form) form, you can get a good idea of ​​the recursive steps.

I do not know if this will help you in solving your problem. I'm currently trying to do something in the same problem area: create a function to “smooth out” nested maps and vectors into a sequence of all paths from root to leaf, each path is a sequence of keys and / or indices ending in a “leaf”.

This library seems to make editing values ​​recursively throughout the structure quite simple. However, I still do not know how to use it to functionally track accumulated data between iterations, which are necessary for my “paths” and probably also for your “skeleton” problem.

+1
source

Source: https://habr.com/ru/post/897339/


All Articles