about adding function `update-if`

106 views
Skip to first unread message

Hiroyuki Fudaba

unread,
Aug 15, 2016, 9:40:07 AM8/15/16
to Clojure Dev
Hi all,

I often get in a situation when I need to update a value in hashmap if it satisfies a predicate, e.g.

```
(def p {:name "James" :age 26})
(update p :age #(if (< % 30) (inc %) %))
```

Wouldn't it be nice if we had a function `update-if` in core as we already have ?
Then we can rewrite the code as following:

```
(update-if p :age #(< % 30) inc)
```

Any comments or suggestions are welcome!

Thanks,

Hiroyuki Fudaba

Sean Corfield

unread,
Aug 15, 2016, 12:51:16 PM8/15/16
to cloju...@googlegroups.com
On 8/15/16, 6:40 AM, "Hiroyuki Fudaba" <cloju...@googlegroups.com on behalf of deli...@gmail.com> wrote:

(def p {:name "James" :age 26})
(update p :age #(if (< % 30) (inc %) %))

What I tend to do in situations like that is use cond->

(update p :age #(cond-> % (< % 30) inc))

We also have an in-house version that threads the condition as well:

(update p :age #(condp-> % (< 30) inc))

Sean Corfield -- (904) 302-SEAN -- (970) FOR-SEAN
An Architect's View -- http://corfield.org/

"Perfection is the enemy of the good."
-- Gustave Flaubert, French realist novelist (1821-1880)






Reply all
Reply to author
Forward
0 new messages