Oliver

Oliver

Turning case-do up to 11

Hi.

I’m always looking for ways to make code more manageable, readable, and nice to look at. To this end, matching and the case-do statement have become my favorite tools in doing so.

I often found myself writing code like this:

case condition1 do
   match1 -> case condition2 do
               match2 -> ...

I tried pulling out the inner case-do into a function but that wasn’t “pretty” by any standard in a lot of cases. (In some cases it was definitely needed - one size doesn’t fit all.)

What I do these days looks more like this:

case {condition1, condition2} do
  {match1, match2} -> ...
  {match1, _}      -> ...
  {_, match2}      -> ...
  _                -> ...
end

The only thing I don’t like about this is that you have to repeat sometimes the result of one case in another. Just putting it in front of the case statement makes you compute something that might not be needed. You also cannot emulate this:

case condition1 do
   match1 -> common = ...
             case condition2 do
               match2 -> <do something with common>
               match3 -> <do something with common>

So, combining a case-do with tuples is no panacea. But it can clean up some code considerably.

Though you could do this…

common = fn -> <something common> end

case {condition1, condition2} do
  {match1, match2} -> common.() ...
  {match1, match3} -> common.() ...
  {match1, _}      -> ...
  {_, match2}      -> ...
  _                -> ...
end

Hmmm…

Any additional ideas are very welcome!

Most Liked

NobbZ

NobbZ

Have you tried the with/1 special form?

It is pretty useful to unwrap nested case-expressions.

10
Post #2
Oliver

Oliver

The biggest use of that I see is that it replicates the clean code you get from using the Maybe monad in Haskell-likes. As long as your functions fail by returning something emulating a Maybe - so basically {:ok, result} and {:error, result} and you use when to compute all the expensive parts, then you can basically reap the benefits of Maybe without implementing a new construct for it.

with {:ok, phase1} <- expensive_computation(),
     {:ok, phase2} <- read_something_from_db(phase1),
     {:ok, phase3} <- do_a_file_operation(phase2) do
  phase3
else
  :error -> :error
end

[EDIT: Fixed the operator as suggested by @Qqwy]

I like that. :slight_smile:

The purpose of a Maybe is to “fall through” a computation when any step fails, without forcing the user to riddle the code with error-handling after every step. I don’t know how efficient with/1 is in regard to going to the else branch but it sure matches the elegance of such code without much effort.

You even get to define your own pattern what constitutes a Maybe. It just needs to be conveniently match-able. The Erlang convention of using :ok and :error tuples is hard to beat in this regard.

So, I’ll definitely take with-do-else into how I write code in the future. Thanks!

Qqwy

Qqwy

TypeCheck Core Team

Be warned that with {:ok, result} = something() and with {:ok, result} <- something() mean something different!

With <-, the else will be called when it is not matched (or, if there is no else, the non-matching result is passed on to the outside scope).

With =, a MatchError is raised instead.

Where Next?

Popular in Questions Top

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
Werner
Hi, I’m using Ubuntu 18.04 and after updating to OTP-24.0 yesterday i have this warning when I run “mix local.hex”: 14:57:30.512 [warn] ...
New
dokuzbir
Hello, I am trying to convert my lists to string without losing brackets.For start i have 3 map. They look like these buyer = %{ id: ...
New
hariharasudhan94
I would like to know what is the best IDE for elixir development?
New
myronmarston
The Elixir Typespec docs show the following syntax for keyword lists in typespecs: # ... | [key: type] # keyword lis...
New
makeitrein
Hey all, just started picking up Elixir last week and am writing a scraper as a learning project. Baby step #1 is extracting the number ...
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
baxterw3b
Hi guys, i’m new in the Elixir world, and i have to say, that i love it! i’m having some problem to understand anonymous functions with ...
New
chrisalley
ExUnit now has describe blocks which is a welcome addition coming from RSpec. In the docs, it states that nested hierarchies of describe ...
New
skosch
To my knowledge, put_in, Map.update etc. all have the one limitation of not automatically creating intermediate keys when needed (for exa...
New

Other popular topics Top

gshaw
What is the idiomatic way of matching for not nil in Elixir? E.g., First way: defp halt_if_not_signed_in(conn, signed_in_account) when...
New
sergio_101
I am VERY much an elixir newbie. I have taken one elixir course and one phoenix course on Udemy. During that course, I saw the instructor...
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
mcarvalho
What is the difference between System.get_env and Application.get_env? For example, what are best practices to use one versus another.
New
mgjohns61585
Could someone help me? I'm making my first elixir program, number guessing game. I can't figure out how to convert the user's guess from ...
New
Patoshizzle
After calling mix ecto.create I get this error: 17:00:32.162 [error] GenServer #PID&lt;0.412.0&gt; terminating ** (Postgrex.Error) FATAL...
New
Qqwy
Original source of discussion: This topic on the Pragmatic Programmers' Functional Web Development with Elixir, OTP, and Phoenix forum. ...
New
lucidguppy
I have a super simple question about elixir - how would I take a file like this foo bar baz and output a new file that enumerates th...
New
TunkShif
This post is an instruction guide to help you setup your Neovim for Elixir development from scratch. It includes general information on h...
273 38985 115
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

We're in Beta

About us Mission Statement