Fl4m3Ph03n1x

Fl4m3Ph03n1x

Background

I am trying to up my Functional Programming (FP) skills and one of the things that newcomers first learn in FP is the Option Type (aka, Maybe Monad).

Option what?

This construct is present in many languages, Haskell has Maybe and Java and Python (yes, Python!) have Optional.

Basically this type models a value that may or may not be there.

How it all comes down to Elixir

Most FP languages have comprehensions, Scala and Elixir have the for construct while Haskell has its famous do notation.

In Scala and Haskell, these comprehensions work not only with Enumerables (such as Lists) but also with our Option type (which is not an enumerable).

I mention this, because according to my understanding, Elixir’s comprehensions only works on Enumerables. Furthermore, as far as I know, there is not Option type datastructure in Elixir.

What does Elixir have?

Elixir has tagged tuples in the form of {:ok, val} or {:error, reason}. Now while Elixir comprehensions can pattern match with tagged tuples:

iex> values = [good: 1, good: 2, bad: 3, good: 4]
iex> for {:good, n} <- values, do: n * n
[1, 4, 16]

It also ignores values that do not pattern match:

iex> values = [good: 1, good: 2, bad: 3, good: 4]
iex> for {:bananas, n} <- values, do: n * n
[]

However, this does not replicate the behaviour of the Option type correctly. Following is an example in Scala:

  for {
      validName  <- validateName(name)
      validEnd   <- validateEnd(end)
      validStart <- validateStart(start, end)
    } yield Event(validName, validStart, validEnd)

Having in mind this signatures:

def validateName(name: String): Option[String]
def validateEnd(end: Int): Option[Int]
def validateStart(start: Int, end: Int): Option[Int] 

The result of the full comprehension expression, should any function return None , will be None.

With Elixir, the bad result would be ignored and the pipeline would simply continue happily ever after.

Questions

At this point I am thinking that implement this Option type as a structure that implements the Enumerable Protocol (so it can be used in Elixir comprehensions) is something that should be possible.

However, I am not sure I want to go down that route if I can simulate similar behavior using tuples.

So I have the following questions:

  1. Is it possible to simulate the Option type using tagged tuples inside Elixir comprehensions?
  2. Are there any Elixir libraries in the wild that have Monadic types (like the one we saw here) usable within Elixir comprehensions? (I know about witchcraft but they have their own construct for comprehensions, which for the time being, I think is a little overkill. I am interesting in something that works with Elixir’s native comprehension functionality).

Showing Posts 1 to 10

ouven

ouven

Hi, I have strong Scala background, but I never missed the for comprehensions or the option type.
Instead I use more pattern matching to solve those problems. So a Scala for comprehension with multiple generators becomes a with statement in my elixir solution space.

Fl4m3Ph03n1x

Fl4m3Ph03n1x OP

The with construct will only execute one line at a time, while the comprehensions will act as nested flatMaps.
While some functionality can be shared between the two (the with construct in elixir is a good way of replacing the Result Monad, for instance) comprehensions are more extensive in that they will apply the results of any given generator to those of the other generators.

For this reason, I am interested in see how far I can push comprehensions and how I can use them.

cmo

cmo

There are a bunch of other versions listed in the readme here.

https://github.com/CrowdHailer/OK

Personally, I do not miss the Option type from F#, though their async and result comprehensions were great. I hated working with the Option/Result type outside of the result comprehension. Noise and ceremony!

LostKobrakai

LostKobrakai

I’m personally not a big fan of how monads are always tought boundled with their specific syntax in language XY. Many monads would be considered way less magicy if people actually tought the idea unrelated to syntax, because as you said a option monad in elixir is usually just a {:ok, term} | {:error, term} tuple, but handled with a bunch of explicit case statements. You can see similarities between Functors and Enum.map.

Generally if you want to have for work with “maybe” in elixir I’d just do this:

for result <- list do
  case result do
    {:ok, x} -> handle_x(x)
    err -> err
  end
end
Fl4m3Ph03n1x

Fl4m3Ph03n1x OP

Please do bear in mind that this dicussions’s purpose is not to focus only on the Option type, I am merely using it because I believe it to be the most well known example to people that do FP.

It is fine for people not liking the Option type, what I am really interested in here is in how I can expand this into other (more useful) types and improve my style with the knowledge gained from trying it both ways :smiley:

Fl4m3Ph03n1x

Fl4m3Ph03n1x OP

Unfortunately, this will not work for multiple generators, unless I have a colossal with statement / case expression at the end for all possible results.

I still appreciate the time you took for your proposal, thank you!

LostKobrakai

LostKobrakai

I’d be really curious for a usecase for that. While in theory I can see the problem in that in practice I’d be wondering why one got to needing it in the first place.

al2o3cr

al2o3cr

Instead of trying to force H-M types into tagged tuples (which they fit most of the time, but not always), what about using a type that already plays nice with Enumerable: a single-element list?

  • Some(A) is then represented by [A]
  • None is represented by []
Fl4m3Ph03n1x

Fl4m3Ph03n1x OP

That is exactly the approach I am using now:

defmodule ParsingWithOption do
  alias Event

  @type option(t) :: some(t) | nothing
  @type some(t) :: [t]
  @type nothing :: []

  @spec validate_name(String.t()) :: option(String.t())
  def validate_name(name) do
    if String.length(name) > 0 do
      [name]
    else
      []
    end
  end

  @spec validate_end(integer) :: option(integer())
  def validate_end(the_end) do
    if the_end < 3000 do
      [the_end]
    else
      []
    end
  end

  @spec validate_start(integer(), integer()) :: option(integer())
  def validate_start(start, the_end) do
    if start <= the_end do
      [start]
    else
      []
    end
  end

  @spec parse(String.t(), integer(), integer()) :: option(Event.t())
  def parse(name, a_start, an_end) do
    for valid_name <- validate_name(name),
        valid_end <- validate_end(an_end),
        valid_start <- validate_start(a_start, an_end) do
      %Event{name: valid_name, start: valid_start, end: valid_end}
    end
  end
end

However, I am not really sure I am happy with the result.
Getting None at the end of the comprehension is a hell lot more friendly (for my brain) then getting [] and then making the link in my head that [] == None.

And this is having in mind that I am using polymorphic typing with dialyzer, which is the coolest thing ever since … (insert cool thing here).

My function signatures are also totally sick, too bad dialyzer can’t make sense of them and actually catch false positives… (but that is a story for another post. gradient is actually being incredibly useful here).

al2o3cr

al2o3cr

Some trivial macros can tidy this up a little, if you’re so inclined:

defmodule Blargh do
  defmacro some(x), do: [x]

  defmacro none(), do: []
end

defmodule BlarghTest do
  import Blargh

  def foo(x) do
    case x do
      some(value) -> some(2*value)
      none() -> none()
    end
  end
end

Where Next? Top

Trending in Questions Top

katta
I having some trouble figuring out if I have set myself too strict of standards for my production server. Currently I can handle 75% of r...
New
brecabral
Documentation While reading the Scoped Routes section, I noticed that the documentation currently refers to a problem without explainin...
New
achenet
Hello, I’m trying to build a basic Phoenix web-app, and I’d like to use Tailwind. However, when I launch mix phx.server, I get an error...
New
kpanic
Hi everyone, I am toying with the idea of building a “match maker” for giving personal help to people that wants to start coding. I sta...
New
asweet-confluent
I recently noticed that Elixir’s Logger defaults its primary log level to :debug when no :logger, :level application configuration is pre...
New
Cxx-mlr
I’m working on a small exercise involving update_in/3, and I came up with this solution: data = %{ name: "Periodic Table", category:...
New
ChrisAmelia
I’ve got trouble wrapping my head around the order in which functions are called in this snippet (from Phoenix’s authentication): toke...
New

Other Trending Topics Top

GenericJam
Edit: 2026 May 15 - This post is archived. Mob is alive!! Main docs: mob v0.7.11 — Documentation A bit of explanation for the slightly c...
New
JesseHerrick
Hey, I’m Jesse and I’m the main contributor behind Dexter, a full-featured, lightning-fast Elixir LSP optimized for large codebases. It s...
New
mudasobwa
I am happy to introduce the very α version of the new programming language compiled to BEAM. Welcome Cure. It has literally three kille...
New
garrison
Hobbes is a low-level distributed database for the Elixir programming language. Hobbes provides a simple, safe, and scalable storage lay...
New
mhanberg
Hi everyone! The first release candidate for the Expert language server project is now available! We’ve published a press release detai...
New
budgie
A little off-topic, but I feel like people here have a good head on their shoulders. I used to be quite good at making software. Was luc...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews