Miyan0

Miyan0

Struggling with having no early return

Hi,

I’m new to functional programming in general and to Elixir in particular. One thing I have some difficulties with is having no early return. I found This article, which works on some cases but not in one like this:

Let’s say I have 3 functions that can return either a value or nil:

get_text(:first)
get_text(:second)
get_text(:third)

I want to stop and get the result from the first function that returns a value (not nil) or nil if all fails.

Something like this works:

  def test_cases() do
    case get_text(:first) do
      value when value != nil ->
        value

      nil ->
        case get_text(:second) do
          value when value != nil ->
            value

          nil ->
            case get_text(:third) do
              value when value != nil ->
                value

              nil ->
                nil
            end
        end
    end
  end

but this looks really bad.

Using cond do works too and looks nicer but require calling each function twice:

  def text_cond() do
    cond do
      get_text(:first) != nil -> get_text(:first)
      get_text(:second) != nil -> get_text(:second)
      get_text(:third) != nil -> get_text(:third)
      true -> nil
    end
  end

I’m sure I’m missing something. Any help with this?

Marked As Solved

zachdaniel

zachdaniel

Creator of Ash

Perhaps controversial but I think this is perfect for a “failing with clause” (I forget what it’s actually called)

def text_cond() do
  with nil <- get_text(:first),
       nil <- get_text(:second) do
    get_text(:third)
  end
end

EDIT: I didn’t recommend the || solution as @hauleth showed, since your problem statement was about nil values, but definitely prefer that over the with.

Also Liked

hauleth

hauleth

You can use || (assuming that these functions do not return boolean)

foo() || bar() || baz()

You can use with:

with nil <- foo(),
     nil <- bar(),
     nil <- baz(),
     do: nil
Miyan0

Miyan0

Thanks a lot. This works great.

Also thanks to all who respond.

Have a nice day.

sodapopcan

sodapopcan

Enum.find_value is an option:

Enum.find_value([:first, :second, :third], fn value -> get_text(value) != nil end)

Or, as per above, assuming get_text returns strings and no booleans:

Enum.find_value([:first, :second, :third], &get_text/1)

But ya, I’m just giving you more to think about. I would also go with ||.

EDIT: I originally suggested the wrong function :grimacing:

Where Next?

Popular in Questions Top

nobody
How to bind a phoenix app to a specific ip address? could not find anything about that, nowhere, unfortunately, but for me this is quite...
New
_russellb
I want to try my hand at web scraping. What tools/libraries do I need to use. I’m hoping to turn this into something professional so don’...
New
vertexbuffer
Hello, can anybody help here..? I have a list of players and I what to delete an element, but every for loop the list is reverting to ori...
New
9mm
I am constructing a JSON object (map) and I need to conditionally set a field. I’m trying to write proper elixir-way code… and I’m at a l...
New
beno
I will often find my self writing things similar to: case some_value do nil -&gt; something() "" -&gt; something() _ -&gt; somethi...
New
Tee
can someone please explain to me how Enum.reduce works with maps
New
RisingFromAshes
I’ve read in another post that it may be possible with a router helper - but I couldn’t find an appropriate one, and tbh, I’m still just ...
New
komlanvi
Hi everyone, I was playing with phoenix liveView but I run into an issue. I have a form and want to validate each input text when the te...
New
earth10
Hi, I’m just starting to build a side-project with Elixir and Phoenix and doing some basic test with Elixir alone. What strikes me is th...
New
vonH
In asking this question I am more interested about the expressiveness of the language itself and less concerned about the availability of...
New

Other popular topics Top

marius95
Hello everyone, I try to use an Javascript Event Handler in my root.html.leex file. Therefore I created a function in the app.js file: ...
New
JeremM34
Hello, how can I check the Phoenix version ? Thanks !
New
shahryarjb
Hello, I have map which I want to convert it to string like this: the map: %{last_name: "tavakkoli", name: "shahryar"} the string I ne...
New
AngeloChecked
What learn first? Rust or Elixir Hi Elixir community! I’m here because i want learn a new language. I’m a junior developer and mainly i ...
New
grych
Hi folks, Few months ago I have announced the proof-of-concept of the library to manipulate the browsers DOM objects directly from Elixi...
639 52774 488
New
jason.o
In the code below, if the create action is not set to accept “extra_key” as an input, it errors out with a message shown above. Is there ...
New
shijith.k
I am trying to start a new phoenix project with elixir 1.9, but mix phx.new does not work. It says that ** (Mix) The task "phx.new" could...
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
AstonJ
Seen any cool LiveView demos, sample apps or examples? Please post them here! :003:
New
JakeBecker
TL;DR: I’ve just released an implementation of Microsoft’s IDE-independent Language Server Protocol for Elixir. It adds language support ...
1144 54250 245
New

We're in Beta

About us Mission Statement