Hacker News new | ask | show | jobs
by wizao 3086 days ago
I know you have got a TON of replies demonstrating better ways to check if a value is null or not. I believe they are all missing the point. In a language with monads, Option's should not be part of the function signature unless it is important to the logic of that function. Your given example should look like:

    func1(a: i32, z: i32) -> i32 {
        return a + z
    }
I know it's not 1 to 1, but the idea is there. You would then use a tiny bit of glue code to combine all the stuff you have to get what you want. For example, if you have 2 nullabes as parameters, you use liftM2; if you have 1 nullable, you use liftM; or perhaps you just want reduce a structure, so you reach for foldM. etc. If your monadic code has to constantly figure out what monad it is, you aren't buying yourself much and I could see why you don't find them valuable. And if the function explicitly needs an Option, then it must be important and must be taken into consideration by the caller. I just don't think they should force the caller to consider them where not needed.

I wanted to mention I often see similar statements with almost the identical code comparison that you made. I believe it has to do with retraining oneself to think functionally instead of imperatively. I'm curious about your background.

For good measure, here's another example in Haskell:

    func1 a b = fromMaybe 0 (liftM2 (+) a b)
And an uglier, but fun, point-free version:

    func1 = (fromMaybe 0 .) . liftM2 (+)
I believe real-world examples would hold up better because the glue code would only be where needed.
1 comments

> Option's should not be part of the function signature unless it is important to the logic of that function.

Yes! Absolutely. Very important observation. In fact in Haskell Maybe should not be part of the signature if you want to return Nothing whenever one of the arguments is Nothing.

> And an uglier, but fun, point-free version

Yikes, please don't! People might get the wrong idea about how good Haskell is written.