Python generators equivalent?

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:

  1. Call a function which takes a RNG, and returns a {randomNumber, newRNG} tuple. This is basically similar to what Enumerable does internally, which @benwilson512 talked about as well.
  2. Specify that you want an infinite stream of random numbers, and take as many numbers from that stream as you need. In this case, the generator is ‘consumed’; you’ve turned in an infinite stream of numbers.

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… :smiley:

2 Likes