Night everyone!
Maybe I'm obsessing over something unimportant, but on the 3rd exercise of the 4th chapter (https://www.braveclojure.com/core-functions-in-depth/), he asks:
> Write a function, validate
, which will check that :name
and :glitter-index
are present when you append
. The validate
function should accept two arguments: a map of keywords to validating functions, similar to conversions
, and the record to be validated.
But it is not clear to me what this function should return. I've built it as a predicate first, but then I realized if he wanted a predicate the function would be called valid?
or something. Then I wrote it in a way that it returns the same map if it is valid, but now false
is appended to the results. This is simple to fix, but it left me wondering if I'm missing an obvious and idiomatic way of writing it.
My first two answers:
(defn valid?
[validator record]
(and ((:name validator) (:name record))
((:glitter-index validator) (:glitter-index record))))
With the function:
(defn append
[new-suspect list-of-suspects]
(cond (valid? validations new-suspect)
(conj list-of-suspects new-suspect)))
And:
(defn validate
[validator record]
(and ((:name validator) (:name record))
((:glitter-index validator) (:glitter-index record))
record))
With the function:
(defn append
[new-suspect list-of-suspects]
(let [validated-suspect (validate validations new-suspect)]
(conj list-of-suspects validated-suspect)))
Where validations is just {:name string? :glitter-index integer?}
.