librelist archives

Fwd: (Без темы)

Fwd: (Без темы)

From:
Nico Balestra
Date:
2013-05-21 @ 12:52
I'm proxying i-blis email :)

----------------------------------------------------

The nice thing with Clojure is that when solving things "the hard way"
(i.e. doing things explicitly) you usually recognize a standard pattern
(and then - may be - the core function or macro that wraps it).

In the case of #38 I saw the reduce straightaway (something like: finding
the max of a list is about folding it over a two-arguments max function).
But I think that even when you first come up with a tail-recursive
solution, you're able to see the reduce pattern in it.

Starting from:

(defn loop-max [ & xs ]
(letfn [ (max-of [a b] (if (> a b) a b)) ]
(loop [s (seq xs) mx (first s)]
(if s
(recur (next s) (max-of (first s) mx))
mx))))

You may say: hey, I walk a seq and recursively combine the result of a
function application in an accumalator, it's a reduce:

(defn red-max [ & xs]
(reduce (fn [a b] (if (> a b) a b)) xs))

------------------------------

This happened to me with another 4Clojure riddle: repeating n times the
elements of a sequence.

I first did this:

(defn replicate [c n]
(when (seq c)
(concat (repeat n (first c))
(lazy-seq (replicate (rest c) n)))))

But recursively building a lazy-seq by mapping the element to a function
(here repeat n %) is what map does (I mean it boils down to (cons (f (first
s)) (map-f (rest s)). Here we indeed merely apply concat to the results of
a map: .

(defn rep [c n] (apply concat (map (partial repeat n) c)))

Looking at the docs, I found mapcat which does exactly that (applying
concat to the results of applying a map to a coll). So, I could write:

(defn r [c n] (mapcat (partial repeat n) c))

Two cents with regards to all, i-blis.

-------- Завершение пересылаемого сообщения --------

-------- Завершение пересылаемого сообщения --------