Skip to content

Instantly share code, notes, and snippets.

@PEZ
Last active March 30, 2024 17:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save PEZ/4e79a8389a4687b2564262b46785d45a to your computer and use it in GitHub Desktop.
Save PEZ/4e79a8389a4687b2564262b46785d45a to your computer and use it in GitHub Desktop.
Map Defaults – Rich 4Clojure Problem 156 – See: https://github.com/PEZ/rich4clojure
(ns rich4clojure.elementary.problem-156
(:require [hyperfiddle.rcf :refer [tests]]))
;; = Map Defaults =
;; By 4Clojure user: jaycfields
;; Difficulty: Elementary
;; Tags: [seqs]
;;
;; When retrieving values from a map, you can specify
;; default values in case the key is not found:
;;
;;
;; (= 2 (:foo {:bar 0, :baz 1} 2))
;;
;;
;; However, what if you want the map itself to contain
;; the default values? Write a function which takes a
;; default value and a sequence of keys and constructs a
;; map.
(def __ :tests-will-fail)
(comment
)
(tests
(__ 0 [:a :b :c]) := {:a 0 :b 0 :c 0}
(__ "x" [1 2 3]) := {1 "x" 2 "x" 3 "x"}
(__ [:a :b] [:foo :bar]) := {:foo [:a :b] :bar [:a :b]})
;; To participate, fork:
;; https://github.com/PEZ/rich4clojure
;; Post your solution below, please!
@amiskov
Copy link

amiskov commented Aug 23, 2021

(def __ (fn [v ks]
          (apply hash-map (interleave ks (repeat v)))))

@evedes
Copy link

evedes commented Sep 7, 2021

(fn [value collection] (into {} (for [x collection] {x value})))

@larscmagnusson
Copy link

larscmagnusson commented Dec 7, 2021

(def __ (fn [default coll]
          (reduce
           (fn [res val]
             (conj res {val default})) {} coll)))

Copy link

ghost commented Oct 5, 2023

(fn [def-value s] 
          (loop [x s
                 result {}]
            (if-not (seq x)  
              result
              (recur (rest x) (conj result {(first x) def-value})))))
              

@aaroncm
Copy link

aaroncm commented Dec 31, 2023

  (def __ #(zipmap %2 (repeat %1)))

@MartinPicc
Copy link

(defn __ [default key-collection]
    (reduce #(assoc %1 %2 default) {} key-collection))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment