Share your thoughts in the 2021 Clojure Community Survey!

Welcome! Please see the About page for a little more info on how this works.

0 votes
in REPL by

Hello,

I have a task to write a function which prints a cartesian product of a single linked list.
This is what my lecturer gave us and it works perfectly,but I just don't understand how they work. More specifically I can't figure out (func (:data node)) this line. I know that it gives us data of the node but what is func doing?
The slist-cartesian function is totally confusing for me.
Please explain to me how they work.
Thank you!

(defn slist-iter [lst func]
(loop [node (deref (:head lst))]

(if (not (nil? node))
  (do
    (func (:data node))
    (recur (deref (:next node)))))))

(defn slist-cartesian [lst]
(slist-iter
lst
(fn [x]

 (slist-iter
  lst
  (fn [y]
    (println x y))))))

1 Answer

0 votes
by
(defn slist-iter [lst func]
  (loop [node (deref (:head lst))]
    (if (not (nil? node))
      (do
        (func (:data node))
        (recur (deref (:next node)))))))

(defn slist-cartesian [lst]
  (slist-iter
   lst
   (fn [x]
     (slist-iter
      lst
      (fn [y]
        (println x y))))))

So, to me, it looks like func is the second argument to slist-iter, which is called by slist-cartesian. At that call site, the second argument is in fact an anonymous function (which CONFUSINGLY also calls slist-iter).

Your confusion is justified.

Here is a simpler implementation:

user> (defn slist-cartesian [lst]
        (doseq [x lst
                y lst]
          (println x y)))
#'user/slist-cartesian
user> (slist-cartesian [0 1 2 3 4])
0 0
0 1
0 2
0 3
0 4
1 0
1 1
1 2
1 3
1 4
2 0
2 1
2 2
2 3
2 4
3 0
3 1
3 2
3 3
3 4
4 0
4 1
4 2
4 3
4 4
nil

I hope you get an 'A'. (:

...