slag-plt / scamper

A mini-Scheme implementation designed for teaching, targeting the web
0 stars 0 forks source link

reduce-right not producing expected results #50

Closed eric-autry closed 9 months ago

eric-autry commented 10 months ago

Below is an excerpt from a student lab. I don't think reduce-right is doing what we expect. Could you check on that behavior?

(define combine (lambda (s1 s2) (string-append s1 " and " s2 " and " s1)))

(define combine-3-right (reduce-right combine (list "A" "B" "C"))) (display combine-3-right)

psosera commented 10 months ago

In terms of the API, this is the intended behavior. Traditionally, for left-folding/reducing accumulator argument is first, but for right-folding/reducing, the accumulator is the second argument. So what we end up with is:

    (reduce-right combine (list "A" "B" "C"))
--> (fold-right combine "C" (list "A" "B"))
--> (fold-right combine (combine "B" "C") (list "A"))
--> (fold-right combine "B and C and B" (list "A"))
--> (fold-right combine (combine "A" "B and C and B") null)
--> (fold-right combine "A and B and C and B and A" null)
--> "A and B and C and B and A"

I'm in favor of updating the documentation to note which argument is the accumulator and which is the current element of the list. Thoughts @eric-autry ?

eric-autry commented 10 months ago

Yeah, updating the documentation would help - and maybe a sort of basic tracing example could help. It accumulates from right to left, but preserves the left-right ordering of the parameters.

eric-autry commented 10 months ago

@psosera