0

I am just started clojure but I can't seem to figure out using/creating higher order functions.

I have partitioned a collection and I want to pass that into another function that will do something to the window of items. I am not sure how to go about doing this.

(def foo [:a :b :c :d :e])

(partition 3 1 foo)
;;=> ((:a :b :c) (:b :c :d) (:c :d :e))

(defn bar [start next end])

I think the basic outline would be.

(defn faz [collect]
    (partition 3 1 collect)
    ;;maybe do here before passing
    (bar stand next end)
)

I might be getting ahead of myself but I also see there are other functions like reduce and apply they can do something similar right? Although, most examples I see have it so they perform operations on two items at a time which are similar to (partition 2 1 foo)

1
  • If you get a single partition bound to e.g. x, then you can call bar on it by using (apply bar x). If you want to get N results of bar from N partitions, then you can use mapv for that (or map if you need laziness or a transducer, but probably not at this point). Commented Nov 20, 2021 at 11:03

2 Answers 2

1

You can do something like

(defn bar [start next end])


(defn faz [collect]
  (let [partitions (partition 3 1 collect)]
    (apply bar partitions)
    ))

or if you want to call bar directly, you can use destructuring

(defn bar [start next end])

(defn faz [collect]
  (let [partitions (partition 3 1 collect)
        [start next end] partitions]
    (bar start next end)
    ))
Sign up to request clarification or add additional context in comments.

Comments

0

Your question is general and there is more ways to achieve this, based on expected result and used function.

If you want to return sequence of results, use map and apply:

(defn results-for-triplets [collect]
  (map #(apply + %) (partition 3 1 collect)))

(results-for-triplets [1 2 3 4 5])
=> (6 9 12)

For better readability, you can use ->> macro.

(defn results-for-triplets [collect]
  (->> collect
       (partition 3 1)
       (map #(apply + %))))

(results-for-triplets [1 2 3 4 5])
=> (6 9 12)

You can avoid apply, if your function destructures passed sequence:

(defn sum3 [[a b c]]
  (+ a b c))

(defn results-for-triplets [collect]
  (->> collect
       (partition 3 1)
       (map sum3)))

(results-for-triplets [1 2 3 4 5])
=> (6 9 12)

If you want to call function for side effect and then return nil, use run!:

(defn print3 [[a b c]]
  (println a b c))

(defn results-for-triplets [collect]
  (->> collect
       (partition 3 1)
       (run! print3)))

(results-for-triplets [1 2 3 4 5])
1 2 3
2 3 4
3 4 5
=> nil

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.