Names for Monadic Modalities

I find myself coming back to a handful of types that I have recently made modules for, and I believe that others have made libraries to work with, and I wanted to see if we could have a discussion about the appropriate names for some types.

The types I keep on encountering and the names that I have chosen for them:

@typedoc """
A nullable value.
""" 
@type optional(a) :: a | nil when a: term()

@typedoc """
The result of an action that can unambiguously fail, e.g. `Map.fetch/2`
"""
@type maybe(a) :: {:ok, a} | :error when a: term()

@typedoc """
The result of an action that fails multi-modally and may be handled per failure mode.
"""
@type either(x, a) :: {:ok, a} | {:error, x} when a: term(), x: term()

What do y’all think?

1 Like

I don’t think maybe or either are the most intuitive names for non-Haskellers. I call your either one result in my projects.

@type result(x, a) :: {:ok, a} | {:error, x} when a: term(), x: term()

By the way, Dialyzer doesn’t unify type variables so that signature is functionally no different from

@type result(x, a) :: {:ok, a} | {:error, a} when a: term()

Or the more idiomatic

@type result(x, a) :: {:ok, term()} | {:error, term()}

Exceptional calls it a TaggedStatus but doesn’t define a @type for it that I could find.

2 Likes

Are you saying there is no functional value to using parameters in types in Elixir?

I can’t think of any, other than it could be shorter in some cases. Sometimes I think it’s good documentation to use the same type var where it should be unified, but it tends to mislead people about Dialyzer’s capability.

I don’t think that these newly defined types make a lot of sense, because it is an extra layer of indirection a newcomer has to get used to when encountering either(x, y) in the return type of a function.

I do think that it would make sense if we somehow standardize the naming for thesee things, however. There are a couple of libraries that work on structures of the shape {:ok, a} | {:error, b} (and the less common {:ok, a} | :error), but there is no real consensus on the naming of these structures.
I think that names like ‘Result Tuple’, ‘OK Tuple’, ‘Error Tuple’, ‘Success Tuple’ are frequently used (by e.g. ok_jose, if_ok, ok, fun_land) but they are not the only ones. I know that exceptional uses ‘tagged status’ to indicate these structures, and maybe there are even others.

For instance, I’m not sure if Witchcraft also defines Maybe/Result monads based on tuples of this specific format, or not.

2 Likes

It defines custom structures. It’s a library of design, not of efficiency. :slight_smile:
(Well not witchcraft itself as it’s a library to build such things, but the ones built on it is.)

1 Like