Skip to content

Instantly share code, notes, and snippets.

@CampingScorpion
Created January 9, 2012 02:18
Show Gist options
  • Save CampingScorpion/1580643 to your computer and use it in GitHub Desktop.
Save CampingScorpion/1580643 to your computer and use it in GitHub Desktop.
work on chatty destructuring of maps
;; TESTS
;; Destructuring arguments
(def actual-plus-one-equals-4 (chatty-checker [actual] (= (inc actual) 4)))
(def vec-structured-checker
(chatty-checker [ [a b & c]]
(and (= a 1)
(= b 2)
(= c [3 4]))))
(def map-structured-checker
(chatty-checker [{:keys [a b]}]
(and (= a 1)
(= b 2))))
(def map-structured-checker-with-as
(chatty-checker [{:keys [a b] :as both}]
(and (= a 1)
(= b 2))))
(fact "chatty checkers can use a destructuring argument"
;; Note: Can't use extended-equality because it swallows chatty-failures
(= (vec-structured-checker [1 2 3 4]) true) => truthy
(= (map-structured-checker {:a 1 :b 2}) true) => truthy
(= (map-structured-checker {:a 10 :b 10}) true) => falsey
(= (map-structured-checker-with-as {:a 1 :b 2}) true) => truthy
(= (map-structured-checker-with-as {:a 10 :b 10}) true) => falsey)
(tabular
(fact "different parts are in fact checked"
(let [result (vec-structured-checker ?actual)]
(= result true) => falsey
(:actual result) => ?actual))
?actual
['x 2 3 4]
[1 'x 3 4]
[1 2 3 4 'x])
(fact "folded results are still shown"
(:intermediate-results (vec-structured-checker ['x 2 3 4]))
=> '( ((= a 1) false)
((= b 2) true)
((= c [3 4]) true) )
(:intermediate-results (map-structured-checker {:a 1 :b 2}))
=> :something)
;; CODE
(defn single-arg-into-form-and-name [arg-form]
(cond (vector? arg-form)
(if (= :as (second (reverse arg-form))) ; use existing as
[ arg-form (last arg-form)]
(let [as-symbol (unique-argument-name)]
[ (-> arg-form (conj :as) (conj as-symbol))
as-symbol]))
(map? arg-form)
(if (contains? arg-form :as)
[ arg-form (:as arg-form)]
(let [as-symbol (unique-argument-name)]
[ (assoc arg-form :as as-symbol)
as-symbol]))
:else
[arg-form arg-form]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment