Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

The Clojure docs regarding (reduce f val coll) state:

If val is supplied, returns the result of applying f to val and the first item in coll, then applying f to that result and the 2nd item, etc.

So I tried:

(reduce str ["s1" "s2"] "s3")

Which leads to:

"[\"s1\" \"s2\"]s3"

However, when I try

(apply str ["s1" "s2"])

I get:

"s1s2"

So why does the vector get converted into its string representation?

share|improve this question
add comment

2 Answers

For a "picture" view for others who may see this question. Clojure's reduce is a left fold. For Haskell programmers foldl.

It creates the following structure

(reduce - 0 (range 1 3))
(- (- (- 0 1) 2) 3)

or infix

(((0 - 1) - 2) - 3)

The intuition being it's a left fold because the parens drift towards the left

share|improve this answer
add comment

Ok, I misread the docs. So reduce actually does this:

(str ["s1" "s2"] "s3")

Which evaluates to:

"[\"s1\" \"s2\"]s3"

Because str needs to convert its arguments to string!

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.