0

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?

asked Sep 17, 2013 at 11:07

2 Answers 2

1

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

answered Sep 17, 2013 at 16:56
1

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!

answered Sep 17, 2013 at 11:11

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.