aadeshere1

aadeshere1

Write while loop equivalent in elixir

I have a another noob question about loop. Since elixir is immutable, while loop is not directly possible.

total = 10
while total != 0
   puts "hello"
   total -= 1
end

The question and answer in this example use list for loop. Convert ruby while loop into elixir

First 10 of 36 Posts! Switch mode

LostKobrakai

LostKobrakai

I found Stream.unfold to be quite useful for places where I don’t know how many iterations are needed to get to the end.

stream = Stream.unfold(10, fn x -> 
  if x != 0 do
    IO.puts "Hello"
    {:ok, x - 1}
  else
    nil
  end 
end)

Stream.run(stream)

There’s also Enum.reduce_while, but it needs an enumerable as input to start with.

10
Post #1
DanCouper

DanCouper

Something like this?

def while(side_effect, i, min) when i == min do
  side_effect
end

def while(side_effect, i, min) do
  side_effect
  while(side_effect, i - 1, min)
end
while((puts "hello"), 10, 0)
tme_317

tme_317

I think recursion is the simplest way to go…

defmodule Looper do
  def say_hello(times_left) do
    case times_left do
      0 ->
        :ok

      x ->
        IO.puts("hello")
        say_hello(x - 1)
    end
  end
end

Looper.say_hello(10)

You could use if instead of case since there are only two patterns.

Alternatively:

defmodule Looper do
  def say_hello(times_left) when times_left > 0 do
    IO.puts("hello")
    say_hello(times_left - 1)
  end

  def say_hello(times_left) when times_left == 0 do
    :ok  
  end
end

Looper.say_hello(10)
peerreynders

peerreynders

defmodule Demo do

  def while(pred, next, data) do
    case pred.(data) do
      true ->
        while(pred, next, next.(data))
      _ ->
        data
    end
  end

  def positive_non_zero?(i),
    do: i > 0

  def say_hello_once(i) do
    IO.puts("hello")
    i - 1
  end

  def demo1,
    do: while(&positive_non_zero?/1, &say_hello_once/1, 10)

  def demo2 do
    data = {1.01, [1.01, 1.02, 1.04]}

    p = fn {i,p} ->
      i in p
    end

    n = fn {last, p} ->
      i = last + 0.01
      IO.puts(i)
      {i, p}
    end

    while(p, n, data)
  end

end

IO.puts("# demo1")
IO.inspect(Demo.demo1())
IO.puts("# demo2")
IO.inspect(Demo.demo2())
$ elixir demo.exs
# demo1
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
0
# demo2
1.02
1.03
{1.03, [1.01, 1.02, 1.04]}
$

Refactoring: Replace Iteration with Recursion
Refactoring: Replace Recursion with Iteration

Recursion to Iteration Series
Recursion? We don’t need no stinking recursion!

Zesky665

Zesky665

Try this

   def while(1) do 
     puts "hello"
   end

   def while(x) do
     puts "hello"
     while(x-1)
   end
sribe

sribe

I just want to comment on something, at first glance all the solutions posted on this page look kind of complicated for such a simple thing. But you almost never need to write such code in the real world.

In actual apps, you want to iterate over some collection of data items. The for or while loop is how you do that in an imperative language: you have some “iterator” kind of value–a simple index for an array, something else for a map or set–increment that, check if it’s out of range, use it to access your data collection.

In functional languages, you pass the operation you want to perform on the data as an argument to one of the collection’s functions. In Elixir, Enum.map or Enum.reduce. This actually results in more compact code because it eliminates the whole “get an iterator, increment, check it, use it” dance.

So while this particular exercise can help you understand some low-level mechanics of Elixir, it could also be misleading. Please don’t think you have to jump through the hoops of all these solutions in order to do something with an array of values you get back from your database or submitted from a web form :wink:

That said, here is my solution:

Enum.each(10..1, fn(i) -> IO.puts(i) end)

or, using some shorthand:

Enum.each(10..1, &(IO.puts("#{&1}")))

or, if you want to prove you actually understand passing around functions:

Enum.each(10..1, &IO.puts/1)

But even that could be misleading, because in a functional language you don’t often just “run a loop” over a collection for side effects, you usually produce a value, either a set of values produce from each source value (Enum.map) or a single value derived from the whole set (Enum.reduce).

13
Post #6
sribe

sribe

Almost, but not quite :wink:

  def while(0) do
  end

  def while(x) do
     puts "hello"
     while(x - 1)
  end

And in real life, you probably want def while(x) when x > 0 do

sribe

sribe

@Zesky665 Haha, you & I were correcting at the same time!

peerreynders

peerreynders

However by bypassing the “low-level mechanics” (and going straight for higher order functions) you are giving up on the opportunity to explore the general connection (and differences) between recursion and iteration, for example:

  • how iteration fundamentally relies on mutability to operate
  • while recursion accomplishes the the same job in an immutable environment[**]

Granted that lesson seems more important in an environment where mutability is a possible choice - where it might be prudent to be “Immutable where possible, mutable (only) when needed”.

[**] which is how the basic HOFs operate.

look kind of complicated for such a simple thing.

Another matter is that a while loop isn’t just one single concept. There is the idea of

  • the body that is executed
  • the predicate which determines whether the body is executed (again)

So the concept of a while loop may actually be seen as more basic than it actually is just because certain programming languages offer a single statement or expression as a representation for it.

Zesky665

Zesky665

You’re right, I always forget that you can just leave a function empty and it won’t cause an error.

Last Post!

thbar

thbar

An equivalent with potentially infinite running time (useful when polling an API for results in a quick Mix.install/2 script):

Stream.unfold(1, fn
  acc ->
    :timer.sleep(1_000)
    IO.puts("Waiting...")
    # TODO here: poll API and decide based on output status whether to leave or not
    if acc >= 5, do: nil, else: {acc, acc + 1}
end)
|> Stream.run()

Thanks @LostKobrakai for the inspiration, I wouldn’t have thought about Stream.unfold for this!

Where Next?

Trending in Questions Top

jonnycharles
I’m in search of an Elixir library that offers PDF generation capabilities similar to Ruby’s Prawn. While there have been discussions abo...
New
spammy
I’m looking to build a personal workflow to quickly deploy web applications written in elixir/phoenix, for local consumption (ie not on t...
New
silverdr
Using Phoenix.LiveView.TagEngine as an EEx.Engine is deprecated! To compile HEEx, use Phoenix.LiveView.TagEngine.compile/2 instead. Sta...
New
saveman71
Hello ! We want new/edit form pages to POST/PUT to their own URL rather than the resources REST defaults (post /things, put /things/:id)...
New
dli
Before I dive in myself, did anyone successfully sprinkle Hologram into their existing LiveView app? Looking for hints regarding: Addi...
New
bottlenecked
Hi all, I wanted to ask how the community is dealing with post-release steps. Today we have Ecto migrations, which make sure that the db...
New
michallepicki
I am using Oban and occasionally, shortly after a deployment, a handful of jobs can fail because of dependency on other parts of the syst...
New

Other Trending Topics Top

JesseHerrick
Hey, I’m Jesse and I’m the main contributor behind Dexter, a full-featured, lightning-fast Elixir LSP optimized for large codebases. It s...
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
Damirados
Hello everyone. After busy few months I am happy to announce v0.1.0 of Emerge & Solve. They are GUI (Emerge) and State management (S...
New
ausimian
Emily is an Elixir library that runs Nx computations on Apple’s MLX. Install it as the default Nx backend and Nx, defn, Axon, Nx.Serving,...
New
type1fool
I just stumbled on a newly redesigned elixir-lang.org. :tada: It looks like @Software_Mansion did the work, and I think it is generally a...
New
akoutmos
@hugobarauna and I (Alex Koutmos) have been hard at work on writing a book on Nerves that takes you from simply blinking LEDs to building...
New

We're in Beta

About us Mission Statement