Card destruction in clojure - unused keys

I defined a function that takes a mapping. I thought of using destructuring to access values. However, I also want to check if there are any keys used.

So, for example, something like ...

(defun func1 [{:keys [abc] :rest rest}] (println abc) (println rest)) (func1 {:a 1 :b 2 :c 3 :d 4}) 

which prints

  1 2 3 4 

The reason I want this is because if rest is not null, this is probably the error I would like to signal. I know about: how, what could I use. But then I need to save the list of valid keys twice.

Did I miss something?

Phil

+6
source share
3 answers

I really don't understand why you will ever want to find out if there are things that you don't care about. If you are trying to do something like “do something specific with these keys and do something in common with others”, you can do something like:

 (defn func [& {:keys [ab] :as args}] (println abc) (println (dissoc args :a :b))) (func :a 3 :b :c 5) => 3 4 {:c 5} nil 

If you are paranoid about having to specify keywords twice, maybe you can do something too, but I can’t imagine that would be useful.

The reason I want this is because if rest is not null, this is probably the error I would like to report.

If you are concerned that users are not exactly what you need, then perhaps the map is not a suitable data structure.

+5
source

If you need to provide a structure structure for a given map, Schema may be a good choice (first example from README ):

 (ns schema-examples (:require [schema.core :as s :include-macros true ;; cljs only ])) (def Data "A schema for a nested data type" {:a {:bs/Str :cs/Int} :d [{:es/Keyword :f [s/Num]}]}) (s/validate Data {:a {:b "abc" :c 123} :d [{:e :bc :f [12.2 13 100]} {:e :bc :f [-1]}]}) ;; Success! (s/validate Data {:a {:b 123 :c "ABC"}}) ;; Exception -- Value does not match schema: ;; {:a {:b (not (instance? java.lang.String 123)), ;; :c (not (integer? "ABC"))}, ;; :d missing-required-key} 
+1
source

(Phil Lord, OP has no doubt moved on to other issues, but here you can find a solution for anyone who has a similar question.)

You can use count to check if the card has the correct number of keys:

 (count {:a 1 :b 2 :c 3 :d 4}) ;=> 4 

Returns the number of key / shaft pairs. While you separately check if the card has the required keys, knowing that too many keys will tell you if there are any additional keys.

0
source

All Articles