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

Most Liked

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 #7
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 #2
benwilson512

benwilson512

Author of Craft GraphQL APIs in Elixir with Absinthe

@silverdr OK sure, here’s a non manual loop version:

Stream.repeatedly(&generate_name/0) |> Stream.take(16) |> Enum.find(&not_taken?/1)

This will return the first generated name that isn’t taken, OR quit after 16 tries. It will only generate as many names as are needed. Enumerable works great here too. Of course, you can always use manual recursion.

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!

Where Next?

Popular in Questions Top

srinivasu
How to handle excepions in elixir? Suppose i have A, B, C ,D, E modules. and each module has get() function. A.get() method will call th...
New
yawaramin
In the Dialyzer docs ( http://erlang.org/doc/man/dialyzer.html#requesting-or-suppressing-warnings-in-source-files ), there is a way to tu...
New
tduccuong
Hi, is there any work on GUI with Elixir, that is similar to Electron/Javascript? My idea is to bundle Phoenix and BEAM into a single se...
New
Werner
Hi, I’m using Ubuntu 18.04 and after updating to OTP-24.0 yesterday i have this warning when I run “mix local.hex”: 14:57:30.512 [warn] ...
New
logicmason
Hi there, I'm working through my first release with elixir/phoenix. I've built a release with distillery and found that it crashes when I...
New
Jim
As a follow up to my earlier question: I have the code compiling and running but not getting a successful login from the rest server. ...
New
hariharasudhan94
I would like to know what is the best IDE for elixir development?
New
mcarvalho
What is the difference between System.get_env and Application.get_env? For example, what are best practices to use one versus another.
New
baxterw3b
Hi guys, i’m new in the Elixir world, and i have to say, that i love it! i’m having some problem to understand anonymous functions with ...
New
hpopp
To simplify some tasks at work, I wrote and published this package yesterday. It’s a simple macro that enables Access behaviour on struct...
New

Other popular topics Top

senggen
Erlang/OTP 25 [erts-13.2.2] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] 15:22:35.803 [error] gen_event {lager_file_backend...
New
sergio_101
I am VERY much an elixir newbie. I have taken one elixir course and one phoenix course on Udemy. During that course, I saw the instructor...
New
malloryerik
Hi, this is for people who, like me, have had some friction using .html.heex templates in VSCode. The solution seems to be, in a hyphena...
New
stefanchrobot
What’s the safe way to decode a JSON string into a struct? I want to avoid calling String.to_atom. Jason.decode can give me a map with st...
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
johnnyicon
Hi all, I've just started learning Elixir and Phoenix Framework, so please pardon my n00bness at this stage. I'm trying to use Postg...
New
chrisalley
ExUnit now has describe blocks which is a welcome addition coming from RSpec. In the docs, it states that nested hierarchies of describe ...
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
AstonJ
by Lance Halvorsen Elixir and Phoenix are generating tremendous excitement as an unbeatable platform for building modern web application...
460 27162 124
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