Daniel Kaplan
Daniel Kaplan

Reputation: 67554

Reducing a sequence into a shorter sequence while calling a function on each adjacent element

I've got a function that looks at two of these objects, does some mystery logic, and returns either one of them, or both (as a sequence).

I've got a sequence of these objects [o1 o2 o3 o4 ...], and I want to return a result of processing it like this:

Here's what I've got so far:

; the % here is the input sequence
#(reduce update-algorithm [(first %)] (rest %))

(defn update-algorithm
  [input-vector o2]
  (apply conj (pop input-vector)
    (mystery-function (peek input-vector) o2)))

What's an idiomatic way of writing this? I don't like the way that this looks. I think the apply conj is a little hard to read and so is the [(first %)] (rest %) on the first line.

Upvotes: 3

Views: 99

Answers (1)

Michał Marczyk
Michał Marczyk

Reputation: 84379

into would be a better choice than apply conj.

I think [(first %)] (rest %) is just fine though. Probably the shortest way to write this and it makes it completely clear what the seed of the reduction and the sequence being reduced are.

Also, reduce is a perfect match to the task at hand, not only in the sense that it works, but also in the sense that the task is a reduction / fold. Similarly pop and peek do exactly the thing specified in the sense that it is their purpose to "keep the butlast" and "take the last" of what's been accumulated (in a vector). With the into change, the code basically tells the same story the spec does, and in fewer words to boot.

So, nope, no way to improve this, sorry. ;-)

Upvotes: 3

Related Questions