hi everyone:
I use Clojure to solve SICP 2.22
<http://www.billthelizard.com/2011/01/sicp-221-223-mapping-over-lists.html>
.
The problem is to rewrite a map fn in a iterative way,here it want to get
the square of each element in a list
Method 1:
(defn square-list [items]
(defn iter [things answer]
(if (empty? things)
answer
(iter
(rest things)
(cons (square (first things)) answer))))
(iter items nil))
This method just return opposite result.
(square-list (range 1 10))
;===>(81 64 49 36 25 16 9 4 1)
I think all I need is to swap the position of (square (first things))
andanswer,then
I can get the right order
I write fn below:
Method 2
(defn square-list [items]
(defn iter [things answer]
(if (empty? things)
answer
(iter
(rest things)
(conj answer (square (first things))))))
(iter items nil))
However, it still return opposite order.
Did I misuse cons and conj or I ignore something?
--
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to [email protected]
Note that posts from new members are moderated - please be patient with your
first post.
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en
---
You received this message because you are subscribed to the Google Groups
"Clojure" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
For more options, visit https://groups.google.com/d/optout.