Fork me on GitHub
#meander
<
2021-03-18
>
Panel02:03:15

Is there a native way to avoid including a key in a map when the value would match nil ?

jimmy03:03:05

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

jimmy03:03:37

Did you want to do that or did you want to check for a key that is explicitly nil?

jimmy03:03:00

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)

jimmy03:03:33

(If neither of these are right feel free to give some examples)

Panel05:03:07

Thanks for the answer (m/match{:a nil :b 2} {:a ?a :b ?b} {"a" ?a "b" ?b}) ;; => {"a" nil, "b" 2}

Panel05:03:06

What I'm looking for is a way to instead return this : ;; => {"b" 2}

Panel05:03:07

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])

Panel05:03:46

But then we are losing the idea of keeping the shape of the output data.

noprompt16:03:46

Are you searching for a submap m such that for all k (string? (get m k))?

noprompt16:03:35

If so you can use

(m/rewrite {,,,}
  (m/submap-of !key (m/pred string? !value))
  (m/map-of !key !value))

Panel22:03:31

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}

Panel22:03:00

The key "b" was omitted from the output because ?b match a nil.

noprompt22:03:50

(fn f [m]
  (m/find m
    {(m/keyword ?name) (m/some ?x) & ?rest}
    (merge {?name ?x} (f ?rest))

    {_ _ & ?rest}
    (f ?rest)

    _
    {}))

noprompt22:03:53

Using rewrite :

(m/rewrite m
  {(m/keyword ?name) (m/some ?x) & (m/cata ?rest)}
  {?name ?x & ?rest}

  {_ _ & (m/cata ?rest)}
  ?rest

  _ {})

jimmy22:03:12

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))

Panel10:03:37

Thanks you both, I read thru the chat log of the past few months and the support you are providing is exceptional.

❤️ 7