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.

Where Next?

Popular in Questions Top

vertexbuffer
Hello, can anybody help here..? I have a list of players and I what to delete an element, but every for loop the list is reverting to ori...
New
New
mgjohns61585
Could someone help me? I’m making my first elixir program, number guessing game. I can’t figure out how to convert the user’s guess from ...
New
ovidiubadita
Hey all, I discovered Elixir and I love it. I always wanted to learn a functional programming and I intended to go for Haskell, but afte...
New
jononomo
I am trying to figure out how Mix knows whether the environment is test, dev, or prod – where is this set? Thanks.
New
earth10
Hi, I’m just starting to build a side-project with Elixir and Phoenix and doing some basic test with Elixir alone. What strikes me is th...
New
joeerl
Hello again - after a longish gap I’ve decided I really must dig into Elixir and see what’s been happening here - so I have a few questio...
New
SoCreat
i’m a new one to elixir which editor can i use vs code? or atom? Thanks! :smiley:
New
rms.mrcs
Hi, I need to transform a list of numbers into a map where the keys are the indexes and the values are the original values of the list. ...
New
jononomo
For some reason my phoenix channels are working for me in my local dev environment, but as soon as I deploy via Docker, I get a 403 error...
New

Other popular topics Top

danschultzer
None of the current solutions worked well for me, so I went ahead and built a user management system from scratch. This project took far...
548 29377 241
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
vertexbuffer
Hello, can anybody help here..? I have a list of players and I what to delete an element, but every for loop the list is reverting to ori...
New
sorentwo
Hello! tl;dr Announcing Oban, an Ecto based job processing library with a focus on reliability and historical observability. After spen...
985 42920 311
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
Patoshizzle
After calling mix ecto.create I get this error: 17:00:32.162 [error] GenServer #PID<0.412.0> terminating ** (Postgrex.Error) FATAL...
New
aalberti333
As the title describes, I’m trying to run Enum.map() over a list of key/value pairs, where the value is a map. My data looks like this: ...
New
boundedvariable
I am going through the kafka architecture. All the features what the kafka is providing are already in Erlang. I would like hear your opi...
New
romenigld
I am trying to run a deploy with docker and I successfully runned with this command: docker build -t romenigld/blog-prod . but when I t...
New
svb
Hi! Currently I want to submit a form by pressing the Enter key. However, since my input field is of type “textarea” this is just adds a...
New

Latest on Elixir Forum

Elixir Forum

We're in Beta

About us Mission Statement