Last active
November 7, 2024 22:53
-
-
Save PEZ/fcd991cd17eb81a7e9a42d84a0cda89f to your computer and use it in GitHub Desktop.
Re-implement Map – Rich 4Clojure Problem 118 – See: https://github.com/PEZ/rich4clojure
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| (ns rich4clojure.easy.problem-118 | |
| (:require [hyperfiddle.rcf :refer [tests]])) | |
| ;; = Re-implement Map = | |
| ;; By 4Clojure user: semisight | |
| ;; Difficulty: Easy | |
| ;; Tags: [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 . | |
| (def restricted [map map-indexed mapcat for]) | |
| (def __ :tests-will-fail) | |
| (comment | |
| ) | |
| (tests | |
| [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))) | |
| ;; To participate, fork: | |
| ;; https://github.com/PEZ/rich4clojure | |
| ;; Post your solution below, please! |
With blogscot test correction - here is a version without the when-let to dummy
(def __ (fn [f coll]
(lazy-seq
(when (seq coll)
(cons (f (first coll))
(__ f (next coll)))))))
Works with any number of sequences passed as arguments:
(def __ (fn [f & s]
(if (empty? s)
s
(lazy-seq (if (some empty? s)
'()
(let [[first-seqs rest-seqs]
(reduce
(fn [[first-args rest-args] current-seq]
[(conj first-args (first current-seq)) (conj rest-args (rest current-seq))]) [[] []] s)]
(cons (apply f first-seqs) (apply __ f rest-seqs))))))))
Returns nil when no sequences are passed as arguments.
(defn select [f s]
(lazy-seq
(when-let [[h & t] (seq s)]
(cons (f h) (select f t)))))
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Found a
Syntax error macroexpanding clojure.core/fnon line 26Changing the code to
fixed that issue for me. And here's my solution: