Fork me on GitHub
#clojure-uk
<
2016-09-05
>
thomas08:09:17

@korny congratulations!

korny08:09:38

Current clojure play project: baby names data manipulation 🙂

korny14:09:31

hey folks - quick question. Is there a function like fnil which wraps a function so it returns nil if the first parameter is nil? I’m finding I have to do a lot of (map #(when % (foo %)) things) - where foo throws a NPE if I pass it nil, and things includes some nils

korny14:09:42

I’d like something like map (when-not-nil foo) things) where when-not-nil would just short-circuit if a thing was foo.

dominicm14:09:00

(defn nilf
   [f x & args]
   (when x
     (apply f x args)))
If it doesn't exist in core, this works for me on a quick test ^^

dominicm14:09:30

That formatting, wow.

korny14:09:43

thanks - yeah, it’s easy to write, just hoping for something idiomatic I’d missed 🙂

dominicm14:09:03

I googled a lot, I've never found anything 😞

dominicm14:09:15

Just realised, my function will return nil if you give it false

dominicm15:09:03

So should be (when (not (nil? x))

glenjamin16:09:16

i suspect the more idiomatic thing is to have foo not throw NPEs, usually by making heavy use of core fns

korny16:09:06

@adebesin - I want something that doesn’t call foo if it would call it with a nil. @glenjamin - true, but foo is in someone else’s code 🙂 (and it’s a thin wrapper around Java code anyway)

glenjamin16:09:52

@korny - in that example, what do you do with the leftover nils in the result collection?

korny16:09:06

I keep them - let the caller handle them. So if foo were inc then (map (nilf inc) [1 2 3 nil 4 5]) would return (2 3 4 nil 5 6) ideally.

kazuwal16:09:52

@korny you should treat nil as a value and not throw a npe

korny16:09:54

I’m trying to avoid changing the code that throws the npe, as it’s not my code.

korny16:09:34

anyway, I have to get to a train - thanks for the thoughts folks, it’s really a trivial thing I can do myself, was just hoping for an idiomatic shortcut to save me some keystrokes

kazuwal16:09:57

@korny cool.. also clojure.spec will help you alot with nil 🙂

dominicm16:09:29

@korny: I've looked before. I reached same conclusion as you. This is why many utility libraries exist I guess 😃

martinklepsch21:09:20

@korny @dominicm isn't some->doing pretty much that?

martinklepsch21:09:30

=> (map #(some-> % inc) [1 2 3 nil 4])
(2 3 4 nil 5)