Onor.io

Onor.io

How To Do A For Loop In Elixir (using only recursion)

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)))

Most Liked

thousandsofthem

thousandsofthem

Simplest way i know:

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

12
Post #2
rvirding

rvirding

Creator of Erlang

I also think there is one benefit for basically everyone of implementing various types of loops explicitly using recursion, and that is to understand what is really going on. So while you might most of the time use libraries or provided constructs instead of actually explicitly doing yourself, really knowing what is going will make you a better programmer. It will allow you use libraries and provided constructs in a better way.

Robert

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)))

Where Next?

Popular in Discussions Top

mikl
I wanted to capitalize a string, and tried using String.capitalize(). That generally works well, until you try to capitalize a word like...
New
Nvim
Anybody knows a comprehensive comparison of Django and Phoenix, thanks for the help. Where are they similar? Where do they differ the m...
New
Nvim
Elixir appears to be a superior language to Python. I don’t see any advantage of Python over Elixir. Are there any?
New
pillaiindu
In django there is a cache framework backed by memcached. Rails also puts a lot of emphasis on caching, and even the idea of russian-doll...
New
praveenperera
How We Replaced React with Phoenix By: Thought Bot
New
ricklove
I was just introduced to Elixir and Phoenix. I was told about the 2 million websocket test that was done 2 years ago. From my research, t...
New
PragTob
Hey everyone, this has been on my mind for some time and I’d love your input on it! TLDR: I feel like maps are superioer for storing and...
New
restack_oslo
Hello, Please pardon me for any faux paux. I am 46 and this is my first time on a forum of any kind. I wanted to to get answers from tho...
New
RudManusachi
What configs will make sense to put to runtime.exs? – A bit of how I configure apps: I have generic configs in config/config.exs, dev...
New
jsonify
So, is Heroku the only free option for hosting Phoenix/Elixir at this point? I’m not ready to commit to paying monthly and was wondering ...
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...
274 41539 114
New
gshaw
What is the idiomatic way of matching for not nil in Elixir? E.g., First way: defp halt_if_not_signed_in(conn, signed_in_account) when...
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
vegabook
I’m brand new to Phoenix and I have stripped one of the demo applications to the bone. I just want to get an svg up on the screen. Here i...
New
vrod
I am using the Starship cross-shell prompt – it seems pretty nice, but I get some errors: [WARN] - (starship::utils): Executing command ...
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
axelson
This post is a wiki (feel free to hit the edit button near the bottom right of this post to add your own changes!) This post collects co...
239 47930 226
New
marick
I had some trouble figuring out how to make many-to-many associations work. Once I got it working, I wrote a blog post. Because I’m a nov...
New
Qqwy
Update: How to use the Blogs &amp; Podcasts section You can post links to your blog posts or podcasts either in one of the Official Blog...
3271 126479 1222
New
sergio
Kind of like when jquery came out, it was super necessary. Existing drag and drop libraries have a bunch of baggage to support old browse...
New

We're in Beta

About us Mission Statement