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.

Where Next?

Popular in Questions Top

shahryarjb
Hello, I get Persian date from my client and convert it to normal calendar like this: def jalali_string_to_miladi_english_number(persi...
New
Tee
can someone please explain to me how Enum.reduce works with maps
New
pmjoe
I have a relationship of love and hate with Elixir. Lots of things are just absolutely right, but there are some things that are kind of ...
New
jerry
Good day to you all. I have been struggling to get a query involving like and ilike to work. Can anyone assist me on this, please? pro...
New
aalberti333
As the title describes, I’m trying to run Enum.map() over a list of key/value pairs, where the value is a map. My data looks like this: ...
New
New
Kagamiiiii
Student & New to elixir. Nice language. I want to convert a english character, e.g. “a”, which is stored in a variable, to it’s asci...
New
polypush135
As many of you may have realized by now (sorry for all the posts here) I’ve been working on a db problem where I’m trying to aggregate a ...
New
nsuchy
Hi. I’ve noticed that Windows Powershell has it’s own IEX command and you cannot access Elixir’s IEX due to the conflict. This isn’t a cr...
New
wernerlaude
In AR this is so simple @articles = current_user.articles How to do in Ecto? def index(conn, _params) do current_user = conn.assig...
New

Other popular topics Top

Qqwy
Update: How to use the Blogs & Podcasts section You can post links to your blog posts or podcasts either in one of the Official Blog...
3268 119930 1237
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
pmjoe
I have a relationship of love and hate with Elixir. Lots of things are just absolutely right, but there are some things that are kind of ...
New
bsollish-terakeet
Credo is smart enough to check for (something like) this: assert length(the_list) == 0 with this response: Checking if an enum is empt...
New
aalberti333
As the title describes, I’m trying to run Enum.map() over a list of key/value pairs, where the value is a map. My data looks like this: ...
New
freewebwithme
Using vs code and installed ElixirLS: support and debugger. And I got an error popped up on start up says Failed to run ‘elixir’ comma...
New
beno
I will often find my self writing things similar to: case some_value do nil -> something() "" -> something() _ -> someth...
New
josevalim
Hi everyone, One of the features added to Elixir early on to help integration with Erlang code was the idea of overridable function defi...
New
AstonJ
by Lance Halvorsen Elixir and Phoenix are generating tremendous excitement as an unbeatable platform for building modern web application...
460 27162 124
New
Nvim
Elixir appears to be a superior language to Python. I don’t see any advantage of Python over Elixir. Are there any?
New

We're in Beta

About us Mission Statement