Gonza

Gonza

Hi! Quick question from a guy coming from Javascript:

Whenever I have to handle some conditional behavior, like ‘do something depending on a well-defined flag’, instead of using a switch/case construct or a bunch of if/else, I usually do something like this:

    const thingDoers = {
        thingOne: () => { /* do thing one */ },
        thingTwo: () => { /* do thing two */ },
        thingThree: () => { /* do thing three */ },
        DEFAULT: () => { /* do default thing */ }
    }

Then I just run thingDoers[flag || 'DEFAULT']() and it works for all cases. If I have to add an additional one, is just a matter of declaring a new function, no extra logic involved.

Is this an acceptable/common pattern in Elixir as well, or do we just pattern-match the thing? Is there a better / more idiosyncratic way of doing the same?

Showing Posts 1 to 10

sodapopcan

sodapopcan

Definitely pattern match.

This is a nice use of multi-head functions AFAIC:

def thing_do(:thing_one), do: # ...
def thing_do(:thing_two), do: # ...
def thing_do(:thing_three), do: # ...
def thing_do(_), do: # ...

thing_do(flag) # If `flag` is `nil` it'll hit the last (default) case

You can do the same thing with one function head and a case if you want. It’s the same thing at the end of the day.

Gonza

Gonza OP

Thanks! Looks even cleaner (my main driver for rejecting switch/case and nested ifs)

I’m still learning about Elixir but I’m loving it every day a little more

sodapopcan

sodapopcan

Definitely don’t shy away from case! It’s very commonly used in Elixir. It’s much different than JS’s switch since it deals exclusively with pattern matches (and of course doesn’t need to break).

sodapopcan

sodapopcan

Just adding that your fall-through clause should probably be def thing_do(nil), do: # ... otherwise you could run into some subtle bugs. Since _ will match anything, thing_do(:thang_tree), for example, will successfully hit the default clause. You probably want things to just blow up in that case.

Gonza

Gonza OP

Thanks for the input! That’s a subtle difference, yes, worthy of consideration.
In my particular case, I guess I’d usually just use _ because I’d want to catch all other cases and send them to a virtual black hole. In an express controller, for example, I do something like DEFAULT: () => res.json({success: false, code: 'UNKNOWN_PARAM'}) (just ignore the fact I’m supposed to check beforehand my flags, it’s just an example)
But I see the value in treating nil as a different thing too

sodapopcan

sodapopcan

Yep, I didn’t mean to say you must do it, just consider it :slight_smile: I have a general problem with wording on this site (and in general) :sweat_smile:

Gonza

Gonza OP

Yeah, don’t worry! English is not my native language so I understand when people say they have a problem with words lol. Sometimes I can’t brain either.

sodapopcan

sodapopcan

Unfortunately it is my first language :sweat_smile:

In any event, welcome to Elixir Forums!

derek-zhou

derek-zhou

I’d question the wisdom of pattern matching on nothing but an atom. Seems like unnecessary polymorphism to me. It would had made more sense if there is a tagged record, ie: {:thing_one, some_data}. Just an atom? Where does it come from?

sodapopcan

sodapopcan

Interesting. I don’t know OP’s exact usecase, though I’ve worked on code matching on atoms before. In that case it was mapping well-known atoms to modules. It was basically just a map but using a function to get around compile-conflicts. The atoms came from database strings (I did not design that code and wasn’t there very long, lol). In this case, OP seems to essentially want a map with executable keys, so I think this is ok? If we’re talking about message passing then ya, a single atom probably isn’t very useful. But ya, there might be an even better solution for what OP is after, I just didn’t dig as I didn’t feel up to XY’ing today :upside_down_face:

Where Next? Top

Trending in Questions Top

RSP87
I’m working on a project that simulates the bumbl example in the programming phoenix book. It acts almost like an email client. We have a...
New
kszambelanczyk
Hello! Could someone please give me a help/sample code, how to delete a file from s3 using waffle/waffle_ecto from Phoenix app. I creat...
New
RemyXRenard
I’m seeing that a list inside a Kino.DataTable will be interpreted as a charlist, even if the Kino.configure() is set to charlists: :as_l...
New
velrest
So my question is quite simple and i have found no conclusive answer on forum, google or AI. Should we use :erlang.float for Integer to ...
New
samoloth
Hi, I’ve just set up an application with ash_authentication. There is only magic link strategy for now, so there is no confirmation add o...
New
FlyingNoodle
If a change or preparation module uses Ash.Changeset.get_argument/2 or Ash.Query.get_argument/2 (or any of the other get_argument functio...
New
ryanwinchester
apply_graft/2 doesn’t rewrite an add_many sub-workflow’s deps on an add step. Grafted jobs cancel with “upstream job was deleted” Version...
New

Other Trending Topics Top

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
marciok
Hi there! We created Gust: A task orchestrator inspired by Airflow. For those who have never heard about Aiflow, it’s a Python-based wor...
New
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
Dmk
Xamal is a deployment tool for Elixir apps that deploys native releases to bare metal servers over SSH. It’s a port of GitHub - basecamp/...
New
Damirados
Hello everyone. After busy few months I am happy to announce v0.1.0 of Emerge & Solve. They are GUI (Emerge) and State management (S...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews