Best way of mimicking Scala Option[T] in Julia?

Viewed 171

If think that Scala Option[T] is quite useful to handle some exceptions, so I would like to use this concept in Julia as well.

For example, if we write the following Scala code in Julia,

def div(x: Double, y: Double): Option[Double] = {
  if (y == 0.0) None else Some(x / y)
}

I guess the following code would do the job, but is there any better of doing this?

function div(x:: Float64, y:: Float64):: Array{Union{Float64, Missing}}
  if (y == 0.0)
   [missing]
  else
   [x / y]
  end
end
1 Answers

In Julia, Union is only an untagged union, which makes a bit of a difference.

In your case, missing might be a very idiomatic solution, depending on the application -- the purpose of missing is to get propagated through following operations, like a chain of map would in Scala:

div(1.0, 0) + 1 === missing

can be compared to

div(1.0, 0).map(_ + 1) == None

But note that this happens automatically, until you hit some function that doesn't know missing. (Note that even x == missing evaluates to missing!) Think of propagating null.

The other variant, which is a bit more like Option[T], is Union{Some{T}, Nothing}. This type will force you to explicitely take care of handling both cases: Some needs to be unwrapped, and nothing does not get propagated and will error soon. This has somewhat different semantics, too: missing is more like a N/A value in data handling, while Some/nothing come closer to Option for things that might or might not exist (e.g., the head of a possibly empty list).

Note that often, just Union{T, Nothing} is used. This in most cases makes no difference in semantics, and is easier to handle: due to Union being untagged, T <: Union{T, Nothing}, and values behave just like plain T. But if you need to distinguish a nothing with None semantics from a nothing with T semantics, which can occur in generic functions, you need the additional Some layer to get Some(nothing) and nothing.

Related