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 36 to 27

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!

dominicletz

dominicletz

Creator of Elixir Desktop

To add one more answer here,

I’ve created a macro while macro while | Hex

import While

total = 10

while_with total, total != 0 do
   IO.puts "hello"
   total - 1
end

IO.puts "total is #{total}"

Explanation:
The while_with binds the variable name total to both the expression total != 0 and the body. The body result (last line of body) always becomes the new value for the bound variable, like in a Enum.reduce

   IO.puts "hello"
   total - 1

Addendum:
If you’re only working with globals (or processes) you can also use the simple while without binding a name:

  import While

  ref = :counters.new(1, [:atomics])
  while :counters.get(ref 1) < 10 do
    :counters.add(ref 1, 1)
  end

  IO.puts("Current value is #{:counters.get(ref, 1)}")
sribe

sribe

Key is that the docs for Stream.take start off “Lazily takes…”, meaning elements not evaluated until requested. So it immediately returns, yes, and the return is an enumerable that will yield 16 values, and that enumerable is passed into the Enum.find? call, but the values themselves are not evaluated by the enumerable until requested, if ever.

silverdr

silverdr

I would understand that the “repeatedly” is infinite, but then my first guess would be that the second part “takes” 16 instances from the infinite stream and passes to the third part, which enumerates over them, or so. But it seems like backward thinking in the context.

Right - think it backwards :slight_smile:

dimitarvp

dimitarvp

One good “brain hack” is to think of Enum as “the result of this will be immediately calculated and passed to the next function” and of Stream as “this will be calculated at the first occurence of Enum down the line”.

hauleth

hauleth

Yes, this is commonly known as “streams” or “lazy iterators”. This mean that the values will be computed only as needed and this is common pattern in languages that have “functional” feel (Haskell is lazily evaluated in general, Rust iterators are lazy by default, etc.). Even some “old” languages are getting such features (like Stream in Java).

lucaong

lucaong

That’s the beauty of lazy streams :slight_smile: the original stream is actually infinite, but it only gets realized in a finite number of elements due to Stream.take and Enum.find.

silverdr

silverdr

Huh, that’s all so different from what I am well used to that after many years of successfully doing it for a living (using too many languages/stacks to list) I feel like I am learning programming from scratch again :wink: That’s both refreshingly challenging and intimidating at the same time. For example looking at the line, I wouldn’t guess that it will generate “only as many as needed”. Thanks.

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.

silverdr

silverdr

In a typical case I need one name, which is not yet taken…

… and I want to limit the number of checks so that if I tried - say - sixteen times and still don’t get a valid, non-yet-existing one, I can stop and notify that something’s probably wrong somewhere (namespace exhausted, misconfiguration, generator bug, etc.), instead of trying “forever”.

Where Next? Top

Trending in Questions Top

RSP87
I’m working on a project that simulates the bumbl example in the programming phoenix book. It acts almost like an email client. We have a...
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
nseaSeb
Hello, I know there is an approach for handling lists that allows for optimized traversal, but I can’t recall the specific method (somet...
New
velrest
So my question is quite simple and i have found no conclusive answer on forum, google or AI. Should we use :erlang.float for Integer to ...
New
samoloth
Hi, I’ve just set up an application with ash_authentication. There is only magic link strategy for now, so there is no confirmation add o...
New
FlyingNoodle
If a change or preparation module uses Ash.Changeset.get_argument/2 or Ash.Query.get_argument/2 (or any of the other get_argument functio...
New
brecabral
Documentation While reading the Scoped Routes section, I noticed that the documentation currently refers to a problem without explainin...
New

Other Trending Topics Top

mudasobwa
I am happy to introduce the very α version of the new programming language compiled to BEAM. Welcome Cure. It has literally three kille...
New
marciok
Hi there! We created Gust: A task orchestrator inspired by Airflow. For those who have never heard about Aiflow, it’s a Python-based wor...
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
Dmk
Xamal is a deployment tool for Elixir apps that deploys native releases to bare metal servers over SSH. It’s a port of GitHub - basecamp/...
New
Damirados
Hello everyone. After busy few months I am happy to announce v0.1.0 of Emerge &amp; 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

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews