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
I’m aware of 2 such projects, are there others?
git: GitHub - team-alembic/realworld: A fullstack Phoenix LiveView application with back...
New
I having some trouble figuring out if I have set myself too strict of standards for my production server. Currently I can handle 75% of r...
New
Hi everyone.
My team and I have been working on a fairly modest app based around video streaming and chat, but we’ve landed a customer t...
New
I really like the adapter patterns that ecto, nebulex, waffle, etc. use and would love find something similar for a key management servic...
New
Hello folks!
So at work, we are seeing some situations where we have to define some “fixed” strings that are used across the codebase in...
New
How Can I Optimise Compile Time Dependencies
I have been building an elixir application for about 2 years now. Many modules and files ha...
New
Other Trending Topics
A little off-topic, but I feel like people here have a good head on their shoulders.
I used to be quite good at making software. Was luc...
New
Hey. Is there anyone here who creates agents in their apps? Not talking about using agents, but creating them. I’m finding it pretty diff...
New
I fully migrated to my own harness from Anthropic/Gemini and I think it’s time to share it. Welcome DSH, the DeepSeek Harness, fully writ...
New
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
There has been a thread to discuss the Stack Overflow Developer Survey on this forum every year since 2018, so here’s yet another one for...
New
I love Elixir. It’s one of 2 programming languages I’ve ever fallen in love with.
But I don’t use it anymore.
Serverless was the promis...
New
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #library
- #deployment
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #elixirconf
- #channels
- #exunit
- #discussion
- #code-sync
- #podcasts
- #javascript
- #onsite
- #dialyzer
- #docker
- #authentication
- #ai
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #blog-post
- #elixirconf-us
- #elixir-ls
- #phoenix_html
- #iex
- #graphql
- #genstage
- #websockets
- #supervisor
- #advent-of-code
- #distillery
- #processes
- #elixirconf-eu
- #api
- #forms
- #security
- #metaprogramming










Showing Posts 1 to 10- Show Best Posts
- Show All (oldest first)
- Show All (newest first)
NobbZ
Well, at least for
Enum.split/2s strictness there has been a discussion recently:This also tackles some small bits of your “state” problem.
In elixir I do usually not expect side effects to happen, so
next(s)which returns1on the first call and2on the second without rebindingswould be counterintuitive for me.If you need a central authority handing out free ids, work items, whatever, I do think that is what GenStage has been developed for.
If you really need something as your python thingy (which involves far too much magic for me, I’d expect it to loop forever) then you need to implement it yourself. Some protocol or behaviour and a handfull of macros, and you are ready to release it on hex.
orestis
Thanks for the link.
Re the magic, would you expect:
… to loop forever? It has similar semantics. I think I could probably implement this with the available tools, yes
jwarlander
@orestis, it looks like StreamSplit would mostly have you covered, at least as far your example goes..
First define your iterator(s):
Then call from somewhere:
See my demo repo for the above example, with some output added.
NobbZ
Of course I do expect a stream that has no end to run forever.
Stream.run/1is documented to evaluate the complete stream.As well as I do expect
while true {}to do nothing forever, and not to do a single nothing only when I do ask for it…After reformatting your code, I do see a little bit better what you meant. Still I’d expect that Stream to run forever and to block that process it is run in, but of course you can ask for printing “hi” and doing an otherwise useless addition if you do know the PID of the starting process.
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.
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.
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
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.
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…
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!