Is there a native way to avoid including a key in a map when the value would match nil ?
Are you searching for a submap m
such that for all k
(string? (get m k))
?
If so you can use
(m/rewrite {,,,}
(m/submap-of !key (m/pred string? !value))
(m/map-of !key !value))
For my use case the killer feature is realy to keep the shape of the data because I need to rename the keys . What I am after is a way to not include the key value in the output if the value is nil.
(m/match
{:a nil
:b 2}
{:a ?a
:b ?b}
{"a" ?a
"b" ?b})
=> {"b" 2}
The key "b" was omitted from the output because ?b match a nil.
(fn f [m]
(m/find m
{(m/keyword ?name) (m/some ?x) & ?rest}
(merge {?name ?x} (f ?rest))
{_ _ & ?rest}
(f ?rest)
_
{}))
Using rewrite
:
(m/rewrite m
{(m/keyword ?name) (m/some ?x) & (m/cata ?rest)}
{?name ?x & ?rest}
{_ _ & (m/cata ?rest)}
?rest
_ {})
I will just say you can also just do a post process step. (On my phone) Something like
(into {} (filter second) my-data-after-meanderized))
Thanks you both, I read thru the chat log of the past few months and the support you are providing is exceptional.
Not exactly sure what you mean. Here’s how you can make sure that a value is non-nil.
(m/match {:a 2}
{:a (m/some ?a)}
?a)
;; => 2
(m/match {:b nil}
{:a (m/some ?a)
:b nil}
?a)
;; => non exhaustive pattern match
Did you want to do that or did you want to check for a key that is explicitly nil?
If so, I think the best I can think of is this. Maybe there is a better way?
(m/match {:b nil}
(m/and
(m/pred #(contains? % :b))
{})
:yep)
(If neither of these are right feel free to give some examples)
Thanks for the answer (m/match{:a nil :b 2} {:a ?a :b ?b} {"a" ?a "b" ?b}) ;; => {"a" nil, "b" 2}
What I'm looking for is a way to instead return this : ;; => {"b" 2}
I found this answer in the chat log: (m/search {:foo/a "..." :foo/b "..." :foo/optional nil } {:foo/a (m/pred string? ?value)} [:a ?value] {:foo/b (m/pred string? ?value)} [:b ?value] {:foo/optional (m/pred string? ?value)} [:optional ?value])
But then we are losing the idea of keeping the shape of the output data.