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
Trending in Questions
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
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
Using Phoenix.LiveView.TagEngine as an EEx.Engine is deprecated!
To compile HEEx, use Phoenix.LiveView.TagEngine.compile/2 instead.
Sta...
New
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
Before I dive in myself, did anyone successfully sprinkle Hologram into their existing LiveView app?
Looking for hints regarding:
Addi...
New
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
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
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
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
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
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
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
@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
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #elixirconf-us
- #supervisor
- #advent-of-code
- #distillery
- #processes
- #api
- #forms
- #metaprogramming
- #performance
- #security










First 10 of 36 Posts!
LostKobrakai
I found
Stream.unfoldto be quite useful for places where I don’t know how many iterations are needed to get to the end.There’s also
Enum.reduce_while, but it needs an enumerable as input to start with.DanCouper
Something like this?
tme_317
I think recursion is the simplest way to go…
You could use
ifinstead ofcasesince there are only two patterns.Alternatively:
peerreynders
Refactoring: Replace Iteration with Recursion
Refactoring: Replace Recursion with Iteration
Recursion to Iteration Series
Recursion? We don’t need no stinking recursion!
Zesky665
Try this
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
fororwhileloop 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.maporEnum.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
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).sribe
Almost, but not quite
And in real life, you probably want
def while(x) when x > 0 dosribe
@Zesky665 Haha, you & I were correcting at the same time!
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:
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.
Another matter is that a
whileloop isn’t just one single concept. There is the idea ofSo the concept of a
whileloop 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
You’re right, I always forget that you can just leave a function empty and it won’t cause an error.
Last Post!
thbar
An equivalent with potentially infinite running time (useful when polling an API for results in a quick
Mix.install/2script):Thanks @LostKobrakai for the inspiration, I wouldn’t have thought about
Stream.unfoldfor this!