Onor.io

Onor.io

One question that came up for me when I first started with FP was how to do things that I was able to do in imperative without mutable variables. One that was tricky was trying to figure out how to do a for loop with no mutable variables. There are better ways to do this (which I am sure others will share) but this is what I’d consider the simplest way to do a for loop in Elixir via recursion:

# How to do a "for" loop in Elixir via recursion

defmodule ForLoop do

  def for_loop(count, action) when is_integer(count) and is_function(action) do
    acc = 0
    loop(action, count, acc)
  end

  defp loop(action, count, acc) do
    if acc <= count do
      action.(acc)
      loop(action, count, acc+1)
    end
  end

end

#Simply write out the numbers 0-10
ForLoop.for_loop(10,&(IO.puts(&1)))

Showing Posts 1 to 10

thousandsofthem

thousandsofthem

Simplest way i know:

for x <- 0..10, do: IO.puts x

12
Post #1
jwarlander

jwarlander

If you wanted to implement a for loop as a re-usable concept, for the sake of understanding Elixir, recursion, pattern matching etc, then sure :slight_smile: I might do things very slightly differently;

defmodule ForLoop do

  def for_loop(count, action) when is_integer(count) and is_function(action) do
    loop(action, count, 0)
  end

  defp loop(_action, count, acc) when acc > count, do: :ok
  defp loop(action, count, acc) when acc <= count do
      action.(acc)
      loop(action, count, acc+1)
  end

end

However, in real life I’d just do as @thousandsofthem suggests, or use Enum.each:

Enum.each(0..10, &(IO.puts(&1)))
sztosz

sztosz

That blog entry is irrelevant :wink: Do you really consider your solution to be simplest?

ForLoop.for_loop(10,&(IO.puts(&1)))
Enum.each(0..10, &(IO.puts(&1)))
for x <- 0..10, do: IO.puts x

Try to look at this code like had no knowledge about programming whatsoever, and answer yourself this: Which line describes what is going to happen when you run it best?

There was some passive aggressive PS. here. And it was uncalled for.

Onor.io

Onor.io OP

@sztosz This is what I said:

Take extra note of the part about “via recursion”. Of course there are simpler ways to write that code. I was trying to demonstrate how to write the code with recursion specifically for developers that are new to FP.

Yes, we can tell them to use a for comprehension or an Enum.each. But the point of my post was to share a technique to write that particular construct using recursion.

sztosz

sztosz

Ok, but what is the gain here for programmers new to elixir or even to programming? Recursion is great, but why use it for using for_loop, especially when in your example it is unclear what argument is sent to the action in for_loop call, and also it does not allow you to pass any argument to your action. I think there are many good examples of recursion, and your unfortunately is just an example of over-complicating code.

Onor.io

Onor.io OP

Please share a good example of recursion so I can see how best to go back and edit my example to make it clearer.

Qqwy

Qqwy

TypeCheck Core Team

Underwater, of course, both the for-construct as enumerables use recursion themselves, and are indeed defined similar to your @Onor.io´s program above .

What might be also interesting, is how to emulate a while-loop in Elixir (but this too something that you should not use/need in practice – there are better constructs providing similar functionality):

defmodule While do
  @doc """
  Loops `body` until a value is thrown using `throw/1`
  Passed to `body` is the `starting_value` (which defaults to `nil`) in the first iteration
  in the next iterations, the result of the previous iteration is used as passed parameter.
  """
  def loop(body, starting_value \\ nil) when is_function(body) do
    try do
      iteration_result = body.(starting_value)
      loop(body, iteration_result)
    catch
      thrown_result -> thrown_result
    end
  end

  def random_example do
    result = loop fn ->
      x = :rand.normal
      IO.inspect x
      if x > 1,do: throw x
    end
    IO.puts "Result: #{result}"
  end

  def counter_example do
    loop(fn x -> 
      if x > 100, do: throw "DONE"
      IO.puts x
      x + 1
    end, 0)
  end
end
sztosz

sztosz

defmodule MyList do
  def flatten([]), do: []

  def flatten([ head | tail ]) do 
    flatten(head) ++ flatten(tail)
  end

  def flatten(head), do: [ head ]
end

IO.inspect MyList.flatten([ [1], [ 2, [3] ] , [4]]) # Returns [1,2,3,4]
IO.inspect MyList.flatten([ [], [ [], [3] ] , [4]]) # Returns [3,4]

Taken from Benjamin Tan's Learnings & Writings - Elixir for the Lazy, Impatient and Busy: Part 1 |> Lists and Recursion

defmodule Factorial do  
  def of(0), do: 1
  def of(n), do: of(n, 1)
  def of(1, acc), do: acc 
  def of(n, acc) when n > 1 do: of(n - 1, acc * n)
end

Taken from Comparing Elixir and Go

Those are good examples of recursion. Re-implementing basic loops it not, especially if that loop is not a general purpose loop, and can only be used if only argument for function that loop calls is the inner loop-accumulator. When someone new to programming or Elixir will see that for_loop, he can be tempted to use it, and be confused when simple loop will start to throw errors.

Onor.io

Onor.io OP

No question there are better approaches. I had a novice ask me at a meetup about how to code something with recursion and I was able to answer him but I told him that I almost never use recursion in practice because there are better approaches (like Enum.each and the for comprehension). I was simply trying to provide a small, trivial example of how to emulate a for loop from an imperative language in Elixir.

Onor.io

Onor.io OP

Those are both excellent examples of recursion but considering that I was trying to demonstrate how one could simulate a for loop from an imperative language (something analogous to

for(i=0; i <=10; i++)
{
action();
}

those would not have been the examples I would have picked. I said right from the start that I was solely trying to demonstrate how to do something analogous to an imperative for loop without mutable values.

Where Next? Top

Trending in Discussions Top

AstonJ
The obligatory hello world thread! Who are you and where are you from? :stuck_out_tongue:
4663 61218 595
New
cblavier
Hey there, It’s been more than a year since we started using LiveView as our main UI library and building a whole library of UI componen...
515 12931 101
New
wmnnd
Hey folks, I wanted to share with you a project I’ve been working on for a while: It’s an Open Source (AGPLv3) newsletter tool. Think Ma...
New
raa-ziq
Hi everyone :waving_hand: I wanted to share something I’ve been building — NowBlind, a random chat app designed to help people discover ...
New
sntran
In my third year of college, around 2010, I found Erlang. A few years later, I found Elixir. I liked the ideas at once: many small proces...
New
gtcode
I’ve been tinkering with Lynx (by José) via hold_ledger. I used AI to write the code, a separate specification, the tests, and the Lean p...
New
Ganna
Hi everyone, I have 8 years of production experience with Erlang/OTP and I’m just starting to get to know Elixir. What would you learn f...
New

Other Trending Topics Top

dominicletz
Hey there, I haven’t seen a list of useful Elixir specific skills for the popular AI tools yet so I’m starting one here with my first. ...
New
mudasobwa
I fully migrated to my own harness from Anthropic/Gemini and I think it’s time to share it. Welcome DSH, the DeepSeek Harness, fully writ...
New
KristerV
Hey. Is there anyone here who creates agents in their apps? Not talking about using agents, but creating them. I’m finding it pretty diff...
New
OndrejValenta
(I just needed to vent somewhere and LinkedIn is full of hope, or hype, I’m not sure which exactly) AI dream has many faces, but general...
New
kip
Localize is the next generation localisation library for Elixir. Think of it as ex_cldr version 3.0. The first version will be released ...
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

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews