Examples:
https://en.cppreference.com/w/cpp/utility/optional/value
https://docs.oracle.com/javase/8/docs/api/java/util/Optional...
Examples:
https://en.cppreference.com/w/cpp/utility/optional/value
https://docs.oracle.com/javase/8/docs/api/java/util/Optional...
In many languages that support Optional types as first-class citizens, it is a compile-time error to ignore the fact that it may be null/none. Your code must deal with this, and you won't have any surprise exceptions, even if you are lazy.
Might as well beat up on Java: One of the best belly laughs I had during a debugging session was tracing a `NullPointerException` to the source, and finding that the reference was to an `Optional<T>` that was being used to handle a value that might not be present. Of course, the null reference here was to the `Optional<T>` itself.
There are also also some ergonomic issues. Obvious ones like the lack of pattern matching making them a bit more verbose to work with, of course. But also deeper, more annoying problems, such as Java's standard library lacking a really well-thought-out equivalent to the various abstractions on sequences that are standard in functional languages, and, by extension, functions for operating on them. Though it does have plenty of bits and bobs that were diligently cargo culted on without really capturing the essence of what this stuff is supposed to be about. So, for example, while (at least in Java 8) `Optional<T>` does have its own method called `flatMap`, it doesn't implement `Stream<T>` or offer an easy method for producing a stream. So the idiom of flatmapping a function that returns `Optional<T>` over a sequence to yield a (possibly shorter) sequence of items for which the function returned something, which is so simple and readable in an ML-like language, becomes hopelessly verbose, awkward, and even error-prone in Java.
(Also, Java Streams are, by design, not referentially transparent, so much so that they cannot be made to behave in a referentially transparent way. Which is a total tangent from what I'm talking about here, but does at least give another angle from which to see the depths to which Java misses the point on these sorts of things, and possibly isn't even able to catch it.)
All of which kind of leaves me thinking, "When in Rome, do as the Romans do." Yeah, in hindsight, the ALGOL family of languages' standard method of dealing with cases where a value might not be available is hopelessly fraught with problems. But importing a second approach from a separate language family that split off about 40 years back and started going in a whole different semantic direction into an existing language that already has its own ways of doing things doesn't appreciably improve that situation. It just introduces two competing ways of doing things that end up interacting poorly with each other.
So, to wrap it up: I'm inclined to say that keeping null and just improving the error message when it happens unexpectedly probably is the best band-aid for this problem.
However, they also tend to provide escape hatches for getting at the type directly, which defeats that and will still let you NPE.
If you're given an Optional that's guaranteed to have a value, it's better to call get and blow up if someone violates this invariant than to silently ignore the invalid input via pattern matching or optional chaining.
Crashing is better than silently ignoring logic errors.
Of course, one could ask what's the point of an Optional that's guaranteed to be non-nil. Well, it often happens that there's some relationship between a set of values that's hard/awkward to express via the type system. E.g. a toy example would be that A and B can both be nil, but it also holds that (A == nil) == (B == nil).
There are unsafe methods to extract the value in those rare occasions when you absolutely know it's there, but you seldom need them. You're supposed to map and pattern match. Neither is silent, so I don't understand what you meant.
> Crashing is better than silently ignoring logic errors.
Map and pattern matching are not silent.
----
[0] https://www.oracle.com/technetwork/articles/java/java8-optio... (search for "this is not the recommended way of using Optional", and bear in mind this was for Java 8, which doesn't have pattern matching like Scala or an ML language)
I'm writing a complicated algorithm and am at a point where I know for certain that a given value must be non-nil. Sometimes it can be nil, but at this point it's provably non-nil (E.g. at the end of Dijkstra's algorithm every entry in the distance vector must be non-nil - assuming the graph is connected). The type system can't prove this, but I know that it's non-nil at this point.
So, when I access it, I want the program to fail loud and clear, because it means that I've messed up somewhere. Handling it via map or pattern matching makes no sense here. What would you write in the nil case of the pattern matching anyway? return -1? That's absurd. abort()? That's exactly what get() does.
I think that sort of pattern is a bad code smell, you are propagating doubt where there is none leading to misleading code that has assumptions that differ from what's on the page - obviously I don't have a real example in front of me so there may be good allowances for understanding but I don't find your core premise to be sound and I feel like any counter example would have a lot of work to do to appear convincing.
If it's provably non-nil, use get. But you must provide the proof, and your first reaction must always be "I'm not sure I can assume this".
> What would you write in the nil case of the pattern matching anyway? return -1? That's absurd.
Yes, it's absurd. You don't return this type of sentinel values in statically typed languages with optional types. If you don't need to discriminate the error, sometimes returning Nothing will suffice. If you need the error, you can use an Either type (where traditionally Left is used for the error).
Again, this isn't something I made up. It's how Optionals are used. I suggest you read the link I posted above.
Nope that's bad programming. If you know the Maybe is always there, PROVE IT! Step 1 to proving anything: Make a proposition. In other words, swap out `Maybe a` for `a`. Then prove it upstream. Maybe at some point you want to crash, but you definitely want to do it at the boundary and not within your function. Writing a function that takes a Maybe but assumes it's there just seems like asking to break things.
> a toy example would be that A and B can both be nil, but it also holds that (A == nil) == (B == nil).
Isn't this just `Maybe (A, B)`? If you have both sums and products in your type system, these sorts of situations go away.
A more complicated example: You have A and B and A, B, or both are non-null. But both are never null at the same time.
The way to lift this invariant into your type system (i.e. make a proposition about your program) is:
data IOr a b = ILeft a | IRight b | IBoth a b>If you have both sums and products in your type system, these sorts of situations go away.
Like I said, it’s a toy example. If you need a different example, here’s one: A, B, C and D are Optionals, but at most two of them are nil.
You can write a verbose sum-of-products to encode that ABCD example although if it's really true that only two tops can be nil and it can be any combo and they're all disparate type, I'd love to see what real problem that would be about! Seems nuts.
Lemme see if I can have some fun and encode it more elegantly than "unrolling the permutations" :)
{-# LANGUAGE GADTs #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE KindSignatures #-}
module ABCD where
import Data.Kind (Type)
data N = Z | S N
data AtMostN (n :: N) (ts :: [Type]) where
AMN_Nil :: forall m. AtMostN m '[]
AMN_Pass :: forall t m rest. AtMostN m rest -> AtMostN m (t ': rest)
AMN_Cons :: forall t m rest. t -> AtMostN m rest -> AtMostN (S m) (t ': rest)
Let's try to have two optional booleans but say that at most one can be present: λ: AMN_Cons True (AMN_Cons True AMN_Nil) :: AtMostN (S Z) '[Bool, Bool]
<interactive>:7:1: error:
• Couldn't match type ‘'S m0’ with ‘'Z’
Expected type: AtMostN ('S 'Z) '[Bool, Bool]
Actual type: AtMostN ('S ('S m0)) '[Bool, Bool]
• In the expression:
AMN_Cons True (AMN_Cons True AMN_Nil) ::
AtMostN (S Z) '[Bool, Bool]
In an equation for ‘it’:
it
= AMN_Cons True (AMN_Cons True AMN_Nil) ::
AtMostN (S Z) '[Bool, Bool]
The type error requires some interpretation, but it sees that we set two. Note the ('S ('S m0))We can say at most two are set and now it compiles:
λ: AMN_Cons True (AMN_Cons True AMN_Nil) :: AtMostN (S (S Z)) '[Bool, Bool]
And we can set just one and compile fine as well: λ: AMN_Pass (AMN_Cons False AMN_Nil) :: AtMostN (S Z) '[Bool, Bool]
This is a bare-bones example. We can easily add a lot of sugar on top to make it more ergonomic (maybe even custom type errors)> A, B, C and D are Optionals, but at most two of them are nil.
That sounds like something that's quite fragile and should either be wrapped up in its own type or not depended on.
That's a big leap. That's like saying Haskell isn't pure because of unsafePerformIO. You still get nice static checks with Maybes. If people cheat with fromJust, it's at least obvious they are cheating. Both big and obvious improvements over null :)