Latest news about Bitcoin and all cryptocurrencies. Your daily crypto news habit.
Languages like Haskell are able to deal directly with Infinite Lists, but that can ability be brought to the world of JavaScript?
https://codepen.io/fstokesman/pen/maBBQG
In the real world we deal with âinfiniteâ ideas all the time. All the positive numbers is an example of an infinite concept we wouldnât bat an eye at. But typically when we are programming we have to think of these infinite concepts in a finite way. You canât have an Array of all the positive numbers (at least not in JavaScript!).
What I want to introduce in this article is the idea of an Infinite List data structure, which can represent some never ending sequence, and letâs us use common operations like map and filter to modify and create new sequences.
When we want to actually use the data, we can just take some concrete amount of it.
Creating an Infinite List
To create the kind of structure defined above, we first need some way to just describe an infinite thing without needing to actually evaluate it (which would kill the computer really fast). To do that we first need to understand 2Â things:
- The iterator pattern
- Generator functions
The iterator pattern
Letâs start with the iterator pattern first. The iterator pattern is a kind of design pattern where you can produce a lot of values, one at a time. Itâs basically just an object with a .next() method. When that method is called, it returns another object with 2 keys: value and done. As we call .next(), the done property indicates whether the iterator has more values to give us, and the value is of course the value. Below is a simple iterator that returns values 0 to 3:
This kind of pattern has a first-class place in JavaScript. Arrays, Objects, Maps, and Sets can all implement the iterator pattern by conforming to an interface called Iterable.
Generator functions
Generator functions are a special kind of function in JavaScript which is declared with the function* syntax. Generator functions are used to create iterator objects (ones with a .next() method), but in much clearer and more concise way. Below is a finite generator that creates an equivalent iterator:
Here, the yield keyword is used to indicate the value that is returned every time the iterator is called. You can think of the function pausing after every yield, and picking up where it left off when the iteratorâs .next() method is called again.
All it would take to make this an infinite generator is to turn the while (x < 4) loop into a while (true) loop. For a better feel, hereâs an infinite generator for the famous fibonacci sequence:
Putting it together
Iterators seem like a representation of something infinite because it lets us ask for the .next() element indefinitely. Furthermore, a generator seems like a good way to specify the iterator, because we can write succinct algorithms for infinite series without the boilerplate of manually crafting iterators.
But this still isnât enough, because as powerful as generators are, theyâre not really compositional. If I wanted to to create a generator where I filtered to all the fibonacci numbers that ended with a 5, I canât easily use my existing createFibSeqIterator() to do thatâââi.e. I canât compose the idea of the original generator + some new operation on it.
To remedy this, we first need to encapsulate the generator into a data type, which we can do with a class:
Itâs on this class that we will implement our operations like filter, map, and take.
Infinitely Lazy
You might be puzzled when thinking about how we could implement an operation such as filter. The answer is simple: we do it lazily. Instead of actually trying to filter our list, we just make a note inside the Infinite class. Then when the user wants concretely .take() some elements of it, we can do the actual business of filtering then.
The Infinite class gets a new transformations property, and filter creates a new Infinite with the same generator and transformations array, and pushes a transformation into the list.
We now have all the components we need now to write a .take() that will make the list concrete.
When we call .take(n), we can create an iterator out of the generator, and then initialize a fixed-length array with n elements. This will be our concrete list. An index variable can be used to keep track of how many concrete values weâve collected so far. Using a while loop, we can get a value out of the iterator, and then run our list of transformations on it. If one of those transformations is a filter, and it doesnât pass the test, we simply donât add it to our concrete list, and repeat the loop. When weâve collected n elements, weâre done and can return the concrete list.
Letâs see how that looks with the fibonacci example from before:
To implement map, we could use much the same approach as with filter. The map method itself just clones the current Infinite and adds a new transformation to the list. Inside take, itâs enough to just add an else-if inside the transformation loop.
Conclusion
In this article weâve explored the iterator pattern and generator functions in order to build a compositional and lazily-evaluated Infinite List data structure.
The Infinite List in this article is a bit limited however, because it lacks some operations that would make it truly useful, like a map implementation, dependent filtering, or the ability to combine Infinites together (like pairing every fibonacci number with a prime number, for example).
For these I created lazy-infinite, a more powerful Infinite List structure, that conforms to the Fantasy-Land specification. Iâd love for you to take a look on github, or to give it a try in your next project with
If youâve enjoyed this delve into Infinite Data Structures, Hit me up on twitter @fstokesman, and considering giving this article a đ.
Infinite Data Structures In JavaScript was originally published in Hacker Noon on Medium, where people are continuing the conversation by highlighting and responding to this story.
Disclaimer
The views and opinions expressed in this article are solely those of the authors and do not reflect the views of Bitcoin Insider. Every investment and trading move involves risk - this is especially true for cryptocurrencies given their volatility. We strongly advise our readers to conduct their own research when making a decision.