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?
2 Answers 2
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
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!