Skip to content

Instantly share code, notes, and snippets.

@PEZ
Last active November 7, 2024 22:53
Show Gist options
  • Select an option

  • Save PEZ/fcd991cd17eb81a7e9a42d84a0cda89f to your computer and use it in GitHub Desktop.

Select an option

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
(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!
@blogscot
Copy link

Found a Syntax error macroexpanding clojure.core/fn on line 26
Changing the code to

(fn [_x] nil) (range 10))

fixed that issue for me. And here's my solution:

(defn __ [f coll]
  (lazy-seq
   (when-let [_ (seq coll)]
     (cons (f (first coll))
           (__ f (next coll))))))

@StanTheBear
Copy link

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)))))))

@onstop4
Copy link

onstop4 commented Jan 12, 2023

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.

@oezg
Copy link

oezg commented Nov 7, 2024

(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