stiegi

stiegi

Most elegant way for simple conditions an deconstructions

I would like to have your opinions about a very simple example, because I worked with imperative languages so far only, and I would like to get the mindset of declarative programming.

So i have a function that is called parse_index/1. During runtime we don’t know if we receive an integer or a string as argument, but if it is a string, we want to convert it to a number.
I wrote it like this:

  def parse_index(index) do
    is_number(index)
    |> case do
      true -> index
      false -> Integer.parse(index)
    end
    |> case do
      {number, _} -> number
      number -> number
    end
  end

These are a lot of lines for a pretty simple task, and I was wondering: how small and elegant can you rewrite that by taking advantage of more language features.
It’s really just to learn ‘how to think’ about problems why I ask that, because it kind of feels like I force the imperative way on Elixir when I write it like that…

Thanks!

Marked As Solved

kokolegorille

kokolegorille

Pipe is nice, but too much is ugly :slight_smile:

  def parse_index(string) when is_binary(string) do
    case Integer.parse(string) do
      {number, _} -> number
      :error -> 0
    end
  end

… and if You really wanted to, You should have started with

def parse_index(string) when is_binary(string) do
    string
    |> Integer.parse()
    |> case do
      {number, _} -> number
      :error -> 0
    end
  end

Also Liked

kokolegorille

kokolegorille

Hello and welcome,

You could pattern match on function header…

like this

def parse_index(string) when is_binary(string) do
...
end
def parse_index(number), do: number
LostKobrakai

LostKobrakai

I generally tend to use ecto wherever data enters the system and converting it to a known format/type. E.g. using schemaless changesets:

def parse_something_with_an_index(data) do
  {%{index: nil}, %{index: :integer}}
  |> Ecto.Changeset.cast(data, [:index])
  |> Ecto.Changeset.validate_required([:index])
  |> …
end

changeset = parse_something_with_an_index(input)
case Ecto.Changeset.apply_action(changeset, :validate) do
  {:ok, data} -> # correct data
  {:error, changeset} -> # some errors
end

After that you can go on and do whatever you need to do with the data knowing it’s in the format type you expect it to be in.

stiegi

stiegi

I see, thanks! Prefer without pipes here too

Where Next?

Popular in Questions Top

dotdotdotPaul
Okay, I'm having a heck of a time trying to figure out how to best handle the validation of belongs_to associations in Ecto. I'm sure I'...
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
JorisKok
I have a server on AWS, and was running a load test using artillery. When looking at the Phoenix dashboard I see the Ports going to 100% ...
New
quazar
How to set Jason to encode all fields in ecto schema, I don’t care about security and implementing only is taking long list of attributes...
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
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
vonH
When I run the Plug and I recompile I wind up having to use Ctrl C to quit iex and start again. Witht the help of rlwrap I can use the cu...
New
stefanluptak
Hello everybody, usually, I use a 29" ultra-wide monitor for VSCode which can easily accomodate explorer (files panel) + file with code ...
New
chewm
Hi guys, nice to meet you to the whole forum, I’m new here, I’m trying to configure visual studio code for elixir, right now the intellis...
New
jay1
Why is it that the mnesia database isn’t the most preferred database for use in Elixir/Phoenix?
New

Other popular topics Top

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
belgoros
I’m not a pro in using Regex and can’t figure out why the following behaviour happens, especially if we take into account the difference ...
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
jononomo
I am trying to figure out how Mix knows whether the environment is test, dev, or prod -- where is this set? Thanks.
New
dotdotdotPaul
Okay, I'm having a heck of a time trying to figure out how to best handle the validation of belongs_to associations in Ecto. I'm sure I'...
New
JorisKok
I have a server on AWS, and was running a load test using artillery. When looking at the Phoenix dashboard I see the Ports going to 100% ...
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
KronicDeth
Elixir plugin for JetBrain’s IntelliJ Platform (including Rubymine) This is a plugin that adds support for Elixir to JetBrains IntelliJ...
289 35421 110
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
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