aadeshere1

aadeshere1

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

Showing Posts 1 to 10

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.

Where Next? Top

Trending in Questions Top

Blokh
Hey guys, I’ve got a huge CSV ( around 10 GB ) that needs to be processed hourly Do you guys have any suggestions what is the best prac...
New
kszambelanczyk
Hello! Could someone please give me a help/sample code, how to delete a file from s3 using waffle/waffle_ecto from Phoenix app. I creat...
New
Onor.io
I have what I’ve heard referred to as a “lookup table” in my database. This is a way of assigning codes to common values. One common lo...
New
jaybe78
Hello, I’m developing a online persistent chat system (what’s app) like using elixir/dynamodb/aws for a mobile app(flutter). The diffic...
New
Trolleger
What approach to take when sending live updates to “random” users Hi! I have a question, I have a little chat app, and when I create a DM...
New
matt-savvy
Anyone here using Honeybadger? My Honeybadger account is being overwhelmed with noise from some bots. Seeing a lot of Bandit.HTTPError...
New
RemyXRenard
I’m seeing that a list inside a Kino.DataTable will be interpreted as a charlist, even if the Kino.configure() is set to charlists: :as_l...
New

Other Trending Topics Top

garrison
Hobbes is a low-level distributed database for the Elixir programming language. Hobbes provides a simple, safe, and scalable storage lay...
New
mcass19
ExRatatui lets you cook up rich terminal UIs in Elixir, powered by Rust’s ratatui via Rustler NIFs. Build interactive terminal applicatio...
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
netoum
Corex is an accessible, unstyled UI component library for Phoenix that integrates Zag.js state machines using Vanilla JavaScript and Live...
New
wintermeyer
There are three potential reasons for members of this forum to have a look at https://vutuv.de You are tired or annoyed of LinkedIn. Yo...
New
webofbits
Aludel - LLM Evaluation Workbench Aludel is an embeddable Phoenix LiveView dashboard for evaluating and comparing LLM prompts across mult...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews