3 ms·
I wonder if it's possible to add something similar to the protection you get in Haskell to other languages via some static analyzer or something. In Haskell, i
by jolmg 8y ago
I wonder if it's possible to add something similar to the protection you get in Haskell to other languages via some static analyzer or something.
In Haskell, it's pretty much impossible to have unexpected nulls because the ability to return nulls is something that is expressed in the type and needs to be handled before working with the possible type to be able to pass the type-check of the compiler.
For example, if I had a function:
findFistOdd :: [Int] -> Maybe Int
That returned the first odd number in a list of numbers, the Maybe wraps the return value so the result is either `Nothing` or `Just someNumber`. I can't work with the result directly like
1 + findFirstOdd [2,3]
It would fail the type check, because I need to tell the compiler what the program should do if findFirstOdd couldn't find an odd number. (1 +) is certainly not expecting a NULL as its argument type is Int. I can tell it, "Just die if that happens":
1 + (fromMaybe (error "couln't find odd number") $ findFirstOdd [2,3])
or I can tell it to work on the inside value if it's there, returning Just (1 + someOddNumber) if it's there or Nothing if it's not:
(1 +) <$> findFirstOdd [2,3]
Conversely, if a function says it returns an Int:
addOne :: Int -> Int
That means it returns an Int, guaranteed. That's never going to be some null value. It's not something you'd ever have to consider.
Kind of wish all languages were like this. Nulls are probably the cause of most unexpected exceptions and it could be something that could always be caught without even running the program.
- eckza 8y agoYou’re looking for a nice little functional frontend web language called Elm.
- deleted 8y ago[deleted]
- repolfx 8y agoThat's what Kotlin does. The only place NPEs can creep in with Kotlin code is: a) Interop with Java APIs (Kotlin doesn't force you to check every return type from a non-Kotlin call) b) If you use !! to cast away nullness. Good Kotlin style can almost always avoid such cases.
- oftenwrong 8y agoOptional is Java's impoverished version of Maybe: https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/util/Optional.html https://docs.oracle.com/en/java/javase/12/docs/api/java.base... Of course, an Optional reference can still be null because it's still Java. There are also other implementations of Maybe-like types, and implementations of Either-like types, etc in the Java ecosystem.
- joshmarlow 8y agoI've long loved Option/Maybe types for this reason, but I've recently started to really lean into Result/Either types. When you can return the answer or an error, you can chain the errors together as the error goes up your stack and you have a nice trail leading from the calling code to the violated expectation - sometimes several libraries/abstraction boundaries away!