orestis
So Python has a nice concept of generators - functions that become iterators when called:
def step(x, s):
while True:
yield x
x = x + s
This is called like so:
s = step(1, 2)
s.next() # 1
s.next() # 3
s.next() # 5
And it implements the iterator protocol so you can pass it wherever an iterator is expected.
What’s the idiomatic way in Elixir to do this? We can get partway there with:
s = Stream.unfold(1, fn(x) -> {x, x+2} end)
Enum.take(s, 3) # [1, 3, 5]
But obviously this is not stateful. To get stateful, a process would be needed… But even if we don’t maintain state, I couldn’t find an easy way to do this:
{[1, 3], s} = Stream.split(s, 2)
{[5], s} = Stream.split(s, 1)
Using Enum.split blocks, probably trying to reach the end of the Stream.
Thoughts?
Trending in Questions
Hello!
Suppose you are building workflow (order / task / payment) processing system with the following requirements:
Each workflow con...
New
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
Kia ora,
We have been using elixir-google-api to connect to Google Drive. However, with the updates to Tesla due to CVEs this is now bro...
New
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
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
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
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
Other Trending Topics
Hobbes is a low-level distributed database for the Elixir programming language.
Hobbes provides a simple, safe, and scalable storage lay...
New
ExRatatui lets you cook up rich terminal UIs in Elixir, powered by Rust’s ratatui via Rustler NIFs. Build interactive terminal applicatio...
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
Corex is an accessible, unstyled UI component library for Phoenix that integrates Zag.js state machines using Vanilla JavaScript and Live...
New
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
ICal is a library for interacting with iCalendar data. It parses iCalendars into typed Elixir structs via ICal.from_ics, and can prepare ...
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
- #elixirconf
- #channels
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #blog-post
- #ai
- #phoenix_html
- #elixirconf-us
- #iex
- #graphql
- #genstage
- #websockets
- #supervisor
- #advent-of-code
- #distillery
- #processes
- #api
- #forms
- #hex
- #security
- #metaprogramming











Showing Posts 14 to 5- Show Best Posts
- Show All (oldest first)
- Show All (newest first)
rugyoga
After posting, I realised that my Elixir is ambiguous. It should be:
rugyoga
One of the points of yield/generators in languages like ruby and python is to compute solutions incrementally instead of materializing the solution all at once thus allowing large or even infinite results to be computed. While Elixir doesn’t have yield, it achieves the same goal using Streams. Let me illustrate with a simple backtracking problem: n queens. An inefficient but concise formulation in ruby might go:
The use of yield allows us to use the same code to print one result, all results or count the number of results by supplying a different block to consume then result.
To accomplish the same goal in Elixir, you’d use Streams and flatmap, like so:
Hope that helps.
smpallen99
Just a small note (not sure how on topic it is) about simulating functionality like this is to use a pipeline. I’ve used this approach a number of times in APIs.
peerreynders
I don’t think it’s cheating. It’s taking advantage of the environment’s capabilities. Due to their threaded nature, languages like Python and JavaScript have to have dedicated language constructs for generators.
Joe Armstrong demonstrates building a Future with concurrency features, so if you need a generator - go ahead, use a process (even a GenServer) to build one. I still need to completely digest “To spawn, or not to spawn?” but I’m not advocating going on a spawn-fest; just sometimes it is good to leave the “sequential mindset” behind.
mikulurim
I was reading this thread. I didn’t knwo anything about python, so if you are in my situation this tutorial help me to understand yield in python very quickily.
I love elixir!
Qqwy
The concept of a Generator is not something that is unique to Python. Someone has taken the time in the past to write a version (using message passing) in Erlang (which was also translated to Elixir) on RosettaCode. Interestingly, as the Wikipedia Article mentions, Haskell’s lazily evaluated functions are also generators and as such the Stream that is built-in in Elixir indeed is also a generator.
Of course, in an immutable+pure language, you cannot call the same function with the same value over and over
nextVal(mygen); nextVal(mygen); nextVal(mygen);and expect different results (unless you ‘cheat’ by using message passing). Indeed, when you’re working with for instance a Random Number Generator in Haskell, you have two options:{randomNumber, newRNG}tuple. This is basically similar to what Enumerable does internally, which @benwilson512 talked about as well.In most functional languages (including Elixir), depending on the specific situation, one of these two ways is used. The third one, ‘cheating’ using message-passing, is often too much overhead for what you want to use the generator for. Exceptions of course do exist: A GenServer that returns guaranteed-unique identifiers, for instance.
I do wonder if we can implement a generator based on fixpoint combinators as well, by the way…
orestis
Can’t we all be friends?
Every new language you learn impacts your style. Some concepts tend to stick, so naturally I want to explore how they could be replicated or what the alternatives are.
gon782
Maybe try to leave more of Python land behind or recognize that there are things that are normal in Python that you won’t want to do in Elixir.
orestis
Thanks everyone for your thoughts.
I have currently this passing test case:
This is a toy, of course - mostly an exercise in metaprogramming. I have to admit that having optional parentheses makes things like that fun to write - but I’m not sure how fun it would be if someone did use that in their own code
If i’m not mistaken, Elixir also favors explicit over implicit, which is good from me, coming over from Python land.
benwilson512
An API like
relies upon mutable state. This is obviously impossible with Elixir when using ordinary data structures. Message passing and backing by a genserver could give you something like this, but you’re generally gonna want to avoid that.
There IS a way to get a regular immutable Enumerable to walk forward, but the API is a bit cumbersome because it requires using sort of the “internals” of how Enumerables work.
Not the prettiest way to do that.
At the end of the day though I’d still say that the closest thing to the python
Is the Elixir
And the difference in how you use it is just part of the normal differences you get a in a pure vs impure language.