Skip to content

Instantly share code, notes, and snippets.

@PEZ
Last active March 30, 2024 17:01
Show Gist options
  • 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!
@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