2

I am trying to use the reduce function in a more complex way then what it is usually intended for. I’m not even sure if this is possible, but here’s what I’m trying to do:

Given a list (1 2 3) and two constants, let’s have them be 9 and 13, I’m trying to use reduce to end up with:

(+ 1 (* 9 (+ 2 (* 9 (+ 3 (* 9 13))))))

I tried a method where I added 13 to the back of then list, so I had (1 2 3 13) then tried doing some mapping with Lambda and reduce, but I can’t get the correct answer.

I would post my code that I’ve tried but my internet went out and I’m typing this on my phone, so sorry I can’t show what I tried to do, but the goal is the form of the expression above using reduce

1 Answer 1

3

The proposed operations can indeed be implemented as a reduce (a.k.a. foldr):

(+ 1 (* 9 (+ 2 (* 9 (+ 3 (* 9 13))))))
=> 9739

(reduce (lambda (e acc) (+ e (* 9 acc)))
        13
        '(1 2 3))
=> 9739

Regarding the constants, 13 is used only once in the innermost expression, so it's a good fit to be used as an initial value. 9 is used to multiply the accumulated value. The input list is used from right to left when the recursion starts to unwind, and at that point we add the current element to the accumulated result.

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

1 Comment

And to find the right form during development, you can try something like (lambda (x acc) `(+ ,x (* 9 ,acc))).

Your Answer

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