aochagavia

aochagavia

Idiomatic way to map a result

A common pattern in Elixir is to return {:ok, something} or {:error, something_else} when a function might fail. Sometimes, however, the caller might need to transform the result. Consider for example of a function to divide numbers, which fails when the divisor is 0, and which we want to use as part of a bigger calculation (e.g. divide x by y, then multiply by 42):

case divide(x, y) do
  {:ok, result} -> {:ok, result * 42}
  {:error, _} = error -> error
end

Given all we want is to transform the result in the :ok case, it feels a bit noisy to require a whole case expression here. Some languages provide a map or map_ok function that helps in these situations, which would simplify things down to the following:

divide(x, y)
|> map_ok(fn result -> result * 42 end)

Does Elixir provide something like this? Or would I need to implement my own helper functions? I know it is easy to implement, but it would be cleaner to be rely on the standard library for this.

Most Liked

Eiji

Eiji

As far as I know Elixir does not implements any helper function to work with pipes except Kernel.tap/2 and Kernel.then/2, but those works for all type of input - not only specific one

How about writing a simple macro based on then?

defmodule Example do
  defmacro ok_then(value, fun) do
    quote do
      case unquote(value) do
        {:ok, result} -> {:ok, unquote(fun).(result)}
        result -> result
      end
    end
  end

  def divide(_x, 0), do: {:error, :zero_divisor}
  def divide(x, y), do: {:ok, div(x, y)}
end

require Example

x
|> Example.divide(y)
|> Example.ok_then(&(&1 * 6))
|> Example.ok_then(&(&1 * 7))
|> then(fn
  {:ok, result} -> IO.inspect(result, label: "Transformed result")
  {:error, :zero_divisor} -> IO.warn("Zero divisor problem …")
  {:error, error} -> IO.warn("Unexpected error #{error}")
end)

Using this you can work only on data you are interested and optionally if something fails you can handle all errors in one place.

hauleth

hauleth

There is no strict requirement that :ok or :error will be:

  • tuple
  • with exactly 2 elements

There is plenty of examples where that do not apply:

  • GenServer.start_link/3 can also return :ignore
  • Code.fetch_docs/1 returns :docs_v1-tuple or :error tuple
  • IO.binread/2 can return iodata() on success, unary :error-tuple on error or :eof

Examples like that can be written and written, especially when you add Erlang libraries to the mix. It is hard to have “one catch them all” solution.

I would like to know as well, as functions fits much better there.

Last Post!

Eiji

Eiji

Honestly? I don’t remember. :sweat_smile:

I know that I read about it somewhere. I wrote the code after looking at then/2 macro code. I guess it was something about compile-time optimization like the macro is translated to case at compile time. I tried to find a guide describing it.

Where Next?

Popular in Questions Top

rms.mrcs
Hi, I need to transform a list of numbers into a map where the keys are the indexes and the values are the original values of the list. ...
New
electic
Hi, I am new to Elixir. I am trying to use the DateTime component to insert a date into MySQL however the there seems to be no way to fo...
New
minhajuddin
I have seen a lot of code which picks the first element from a list using Enum.at(0) instead of List.first. Is there a reason why people ...
New
Brian
What is the proper way to load a module from a file in to IEX? In the python world, doing something like this pretty standard: from ....
New
openscript
Hello! Sorry for this astonishing simple question, but I’m really stuck. I try to set up the intellij-elixir plugin, but I don’t know ho...
New
Fl4m3Ph03n1x
About me? ( if you have nothing better to do than reading about some random guy in the internet :stuck_out_tongue: ) Hello all, this is ...
New
WestKeys
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
New

Other popular topics Top

KronicDeth
Elixir plugin for JetBrain’s IntelliJ Platform (including Rubymine) This is a plugin that adds support for Elixir to JetBrains IntelliJ...
289 36654 110
New
aadeshere1
I have a another noob question about loop. Since elixir is immutable, while loop is not directly possible. total = 10 while total != 0 ...
New
chrismccord
Phoenix 1.4.0 released Phoenix 1.4 is out! This release ships with exciting new features, most notably with HTTP2 support, improved deve...
688 31494 112
New
WestKeys
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
New
romenigld
I am trying to run a deploy with docker and I successfully runned with this command: docker build -t romenigld/blog-prod . but when I t...
New
sergio
Kind of like when jquery came out, it was super necessary. Existing drag and drop libraries have a bunch of baggage to support old browse...
New

We're in Beta

About us Mission Statement