orestis

orestis

Newcomer to Elixir, is this idiomatic code? (advent of code solution)

So I’ve started learning Elixir. I took on the Advent of Code challenges, and solved the first day. I’ve skimmed a few books on elixir/erlang, and have had some exposure to FP constructs (including a pleasant semester of Prolog at uni 10 years ago :slight_smile: ).

I came up with the following solution to the day 1 problem. The two test functions showcase what the requirements are (and hopefully the implementation is written such a way what it will be immediately obvious).

Now, after I solved this I searched online to see what other people did. Here are some linked examples:

Reddit Thread
Github 1
Github 2

In those links I see the obvious Enum.reduce approach plus some approaches that seem really weird. I took a classic recursive approach with pattern matching, but only because it’s the feature I prominently remember and I didn’t remember how to write the case construct, so I wanted to see if it would be possible. I have to confess when this code worked, I giggled a bit :slight_smile:

So my question is, is this code considered idiomatic Elixir? The Pythonista in me really likes this code, even if it is a bit more verbose than other solutions. Could I rewrite it to be more idiomatic but keeping the same recursive approach?

Thanks!

defmodule Day1 do
  def santa(s) do
    l = String.codepoints(s)
    santa(l, 0)
  end

  defp santa([], n) do
    n
  end

  defp santa(["(" | tail], n) do
    santa(tail, n + 1)
  end

  defp santa([")" | tail], n) do
    santa(tail, n - 1)
  end

  def test_santa do 
    IO.puts(santa("(())") == 0)
    IO.puts(santa("()()") == 0)
    IO.puts(santa("(((") == 3)
    IO.puts(santa("(()(()(") == 3)
    IO.puts(santa("))(((((") == 3)
    IO.puts(santa("())") == -1)
    IO.puts(santa("))(") == -1)
    IO.puts(santa(")))") == -3)
    IO.puts(santa(")())())") == -3)
  end

  def solve do 
    IO.puts "and now, the punchline"
    {:ok, input} = File.read "day1.input.txt"
    IO.puts(santa input)
    IO.puts(basement input)
  end

  def basement(s) do
    basement(String.codepoints(s), 0, 0)
  end

  defp basement(_, pos, -1) do
    pos
  end

  defp basement(["(" | tail], pos, floor) do
    basement(tail, pos + 1, floor + 1)
  end

  defp basement([")" | tail], pos, floor) do
    basement(tail, pos + 1, floor - 1)
  end

  def test_basement do
    IO.puts(basement(")") == 1)
    IO.puts(basement("()())") == 5)
  end

end


Day1.solve

Most Liked

OvermindDL1

OvermindDL1

I prefer the classic recursive approach as well, though I’d probably align the santa/2 parts to be more like:

  defp santa([], n)           ,do: n
  defp santa(["(" | tail], n) ,do: santa(tail, n + 1)
  defp santa([")" | tail], n) ,do: santa(tail, n - 1)

Two things though, I notice no clause to handle a non-parenthesis, and this is fine for small inputs but huge inputs then might be better without TCO, basically this:

  def santa(s) ,do: s
    |> String.codepoints
    |> do_santa

  defp do_santa([])           ,do: 0
  defp do_santa(["(" | tail]) ,do: santa(tail) + 1
  defp do_santa([")" | tail]) ,do: santa(tail) - 1

All the above code is untested, but is just my way of doing it. :slight_smile:

Also, instead of the testing you are doing there this would be an almost trivial example case for a property testing library if you want to learn something fascinating and useful. :slight_smile:


gregvaughn

gregvaughn

I think that manual recursion approach is something everyone needs to know how to do, and it’s great as a learning exercise. That said, however, I’d expect something more like this in production code:

 def santa(s) do
    s |> String.codepoints
      |> Enum.reduce(0, 
        fn "(", n -> n + 1
           ")", n -> n - 1
        end)
  end
OvermindDL1

OvermindDL1

Correct, but TCO is not free, and I was typing up a long post but I found a good conversation about it on these forums so deleted it and here is the post that describes it in detail and ‘why’ it is the way it is: Tail Call Optimization in Elixir & Erlang – not as efficient and important as you probably think

In essence, an EVM (Erlang VM) process’s stack is also on the heap and they grow toward each other, so it does not matter which you use from a memory perspective, and overall it is more important to keep memory changes down. So in this specific case TCO would not really hurt, but it is not necessary and would likely be faster without TCO since you have bounded inputs.

The only time TCO should really be focused on is when, as per @rvirding as I recall, only when you have unbounded loops, like a receive loop.

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
pgiesin
This should be a simple problem but I just can’t seem to figure it out. I have a standalone Elixir app that won’t find the database. Dep...
New
fireproofsocks
I’m working on defining a simple Ecto schema for a table (in PostGres), but I don’t see where I can define a column as NOT NULL. Conside...
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
rms.mrcs
Hi, I need to transform a list of numbers into a map where the keys are the indexes and the values are the original values of the list....
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
Exadra37
Sometimes I want to check if the input into a function is not a blank string. My first approach: defmodule Example do def do_stuff(s...
New
jc00ke
Expanding on this topic: https://forum.elixirforum.net/t/map-typespec-question/19217 Let’s say I have a map with required and optional k...
New
lanycrost
Hi everyone! I need implement if…else if…else condition from my elixir code, and anymore of this control flow structures not work proper...
New

Other popular topics Top

vonH
In asking this question I am more interested about the expressiveness of the language itself and less concerned about the availability of...
New
William
I would like to know that is there any online source for learning Phoenix Framework for building E-Commerce Store? Any advantage on build...
New
joaquinalcerro
Hi there, I am working with Ecto-Postgresql and I need to call all of the records from a specific table but the table has 40,000 record...
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
ashish173
I am using Ecto timestamps with postgres, I can see the timestamps() use the :naive_dateime but for my use case I wanted to store the ti...
New
fayddelight
I tried installing elixir 1.11.2 erlang 23.3.4 via asdf in my zsh shell. Enabled the versions locally and globally. When I list them ...
New
ovidiubadita
Hey all, I discovered Elixir and I love it. I always wanted to learn a functional programming and I intended to go for Haskell, but afte...
New
Patoshizzle
After calling mix ecto.create I get this error: 17:00:32.162 [error] GenServer #PID<0.412.0> terminating ** (Postgrex.Error) FATAL...
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
siddhant3030
Hi, I have to write a raw query for one of my project. But till now I have used ecto queries and don’t have much experience writing raw ...
New

We're in Beta

About us Mission Statement