Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there standard "foreach" function in Clojure?

Tags:

clojure

Clojure> (doc foreach)
Unable to resolve var: foreach in this context

Clojure> (doc map)
-------------------------
clojure.core/map
([f coll] [f c1 c2] [f c1 c2 c3] [f c1 c2 c3 & colls])

Of course, i can use the "map" to mimic "foreach" but the map always return nil, which makes the output ugly in the following function:

(defn div618 [p1 p2]
    (let [ratio [0.,0.191,0.236,0.382,0.5,0.618,0.809,1.]
          price (fn [r] (if (<= p1 p2) (+ p1 (* (- p2 p1) r)) (- p1 (* (- p1 p2) r))))]

    (if (<= p1 p2)
        (**map** #(println (format "-------%.3f   %.2f-------" %1 (price %1))) (reverse ratio))
        (**map** #(println (format "-------%.3f   %.2f-------" %1 (price %1)))  ratio))))

Sincerely!

like image 729
z_axis Avatar asked Sep 06 '11 02:09

z_axis


4 Answers

I think doseq might be what you're looking for:

(doseq [i [0 1 2 3]] (println i))

However this will still return nil - all forms in Clojure will evaluate to some value; there's no equivalent to Common Lisp's (values).

like image 79
Hugh Avatar answered Nov 19 '22 00:11

Hugh


As of Clojure 1.7 you can use run!:

user=> (run! println (range 10))

0
1
2
3
4
5
6
7
8
9
=> nil  ; returns nil

See this answer to How to print each item of list on separate line clojure?

like image 30
Gordon Gustafson Avatar answered Nov 19 '22 01:11

Gordon Gustafson


You could use doseq or doall. Following is the example using doall.

(defn div618 [p1 p2]
    (let [ratio [0.,0.191,0.236,0.382,0.5,0.618,0.809,1.]
          price (fn [r] (if (<= p1 p2) (+ p1 (* (- p2 p1) r)) (- p1 (* (- p1 p2) r))))]

    (doall (map #(println (format "-------%.3f   %.2f-------" %1 (price %1))) (if (<= p1 p2) (reverse ratio) ratio)))))

You could also separate the printing from the function calculation like this,

(defn div618 [p1 p2]
    (let [ratio [0.,0.191,0.236,0.382,0.5,0.618,0.809,1.]
          price (fn [r] (if (<= p1 p2) (+ p1 (* (- p2 p1) r)) (- p1 (* (- p1 p2) r))))]

    (map (fn [x] [x (price x)]) (if (<= p1 p2) (reverse ratio) ratio))))

(doall (map #(println (format "-------%.3f   %.2f-------" (first %1) (last %1))) (div618 1 2)))
like image 3
Udayakumar Rayala Avatar answered Nov 19 '22 00:11

Udayakumar Rayala


map is used to apply a function f to every element of the seq, in your case your applying print which returns nil, so you get a intermediate seq of nils which you then throw away. When you want side effects like printing you use doseq.

Clojure does not have a single foreach form map, reduce filter etc. technically these are all foreach forms they all do something to each element in the seq. Also map is lazy your example will only print in the repl cause repl forces lazy seq to realize them selfs say if you pack this in a jar it won't do anything.

like image 2
Hamza Yerlikaya Avatar answered Nov 19 '22 02:11

Hamza Yerlikaya