User Tools

Site Tools


lecture:4clojure:core_function_4clojure_problem

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revision Previous revision
Next revision
Previous revision
lecture:4clojure:core_function_4clojure_problem [2013/02/03 05:42]
lispro06 [19. Juxtaposition]
lecture:4clojure:core_function_4clojure_problem [2019/02/04 14:26] (current)
Line 958: Line 958:
  
 문제 문제
 +Difficulty:​ Easy
 +Topics:​ core-seqs
 +
 +
 +Map is one of the core elements of a functional programming language. Given a function f and an input sequence s, return a lazy sequence of (f x) for each element x in s.
 +
 +
 +<​code>​
 +(= [3 4 5 6 7]
 +   (__ inc [2 3 4 5 6]))
 +
 +
 +(= (repeat 10 nil)
 +   (__ (fn [_] nil) (range 10)))
 +
 +
 +(= [1000000 1000001]
 +   ​(->>​ (__ inc (range))
 +        (drop (dec 1000000))
 +        (take 2)))
 +</​code>​
 +
 +Source clojure/​core.clj:​2414 (execution timeout)
 +<​code>​
 +(fn map1
 +  ([f coll]
 +   ​(lazy-seq
 +    (when-let [s (seq coll)]
 +      (if (chunked-seq?​ s)
 +        (let [c (chunk-first s)
 +              size (int (count c))
 +              b (chunk-buffer size)]
 +          (dotimes [i size]
 +              (chunk-append b (f (.nth c i))))
 +          (chunk-cons (chunk b) (map1 f (chunk-rest s))))
 +        (cons (f (first s)) (map1 f (rest s)))))))
 +  ([f c1 c2]
 +   ​(lazy-seq
 +    (let [s1 (seq c1) s2 (seq c2)]
 +      (when (and s1 s2)
 +        (cons (f (first s1) (first s2))
 +              (map1 f (rest s1) (rest s2)))))))
 +  ([f c1 c2 c3]
 +   ​(lazy-seq
 +    (let [s1 (seq c1) s2 (seq c2) s3 (seq c3)]
 +      (when (and  s1 s2 s3)
 +        (cons (f (first s1) (first s2) (first s3))
 +              (map1 f (rest s1) (rest s2) (rest s3)))))))
 +  ([f c1 c2 c3 & colls]
 +   (let [step (fn step [cs]
 +                 ​(lazy-seq
 +                  (let [ss (map1 seq cs)]
 +                    (when (every? identity ss)
 +                      (cons (map1 first ss) (step (map1 rest ss)))))))]
 +     (map1 #(apply f %) (step (conj colls c3 c2 c1))))))
 +</​code>​
 +
  
lecture/4clojure/core_function_4clojure_problem.txt · Last modified: 2019/02/04 14:26 (external edit)