Welcome! Please see the About page for a little more info on how this works.

+6 votes
in Clojure by
edited by

I wonder why there is no function similar to not-empty but for any value with any predicate, like:

(defn when-pred [v pred] (when (pred v) v))

I found this pattern very common and miss it in the core.

Are there reasons for not having it in the core?

JIRA: https://clojure.atlassian.net/projects/CLJ/issues/CLJ-2546

Added 08.09.2022:

1-arity is useful for wrapping predicates

`
(defn when-pred [pred] (fn [v] (when (pred v) v)))

(keep (when-pred pos?) xs)
`

The best name for such function which I found for now is select.

2 Answers

+1 vote
by
selected by
 
Best answer

I've added a jira for this (added to description) and some comments on there.

by
> c) consider arg order (`[v pred]` is probably fine, esp if extending to n preds)

In my projects I use “more natural” order `[pred v]` but looks like `[v pred]` is more “thread-first” friendly.
0 votes
by

Would cond-> fit the bill? Or maybe when-let ?

by
> Would cond-> fit the bill? Or maybe when-let ?

No. Or please show what do you mean.

The main benefit is when `v` is an expression which we should assign a name to:

```
(let [v (get-v)] (when (pred v) v))
; or
(when-pred (get-v) pred)
```

so there is no needless binding in second case.
by
edited by
I think I was thinking of:

    (cond-> v pred identity)

Or if you know what's the next thing you want to do to v you could:

    (cond-> v pred inc)

For example. But cond-> suffer from the same issue that it doesn't thread v into the pred unfortunately. I always wanted a cond-> that did, such as this https://juxt.pro/blog/posts/condas.html
by
...