Introducing foreach (dose) in clojure

I work through SICP - one exercise is to implement foreach (dose). This is an academic exercise . In clojure, this is what I came up with:

(defn for-each [proc, items] (if (empty? items) nil (do (proc (first items)) (recur proc (rest items))))) 

but, I'm a little muddy if do cheating, because do is a special form in clojure, and I don't think there was anything like that in SICP. is there a more minimalistic answer?

Here is another attempt that only executes proc on the last element:

 (defn for-each-2 [proc, items] (let [f (first items) r (rest items)] (if (empty? r) (proc f) (recur proc r)))) 
+6
source share
2 answers

Use doseq and you are all set. For instance:

 (doseq [e '(1 2 3)] (prn e)) 

It will be printed:

 1 2 3 nil 

EDIT:

If you want to implement for-each manually and using as many special forms as possible, here is another alternative, although it ends up almost as short as yours:

 (defn for-each [fl] (cond (empty? l) nil :else (do (f (first l)) (recur f (rest l))))) 

Interestingly, the same procedure could be written more briefly in Scheme, the Lisp dialect used in SICP:

 (define (for-each fl) (cond ((null? l) null) (else (f (first l)) (for-each f (rest l))))) 
+3
source

Here is my attempt. It just executes the function in the inner loop.

 (defn for-each [fun, xs] (loop [fun fun xs xs action nil] (if (first xs) (recur fun (rest xs) (fun (first xs))) xs))) 
+1
source

Source: https://habr.com/ru/post/909403/


All Articles