Created
October 27, 2014 09:28
-
-
Save CMCDragonkai/c9e9bd6b07c4172eaa39 to your computer and use it in GitHub Desktop.
Nix: Lazy Linked List Implementation using Nested Attribute Sets. This example specifically reifies the fibonnaci sequence into a lazy linked list.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# nix lists are not lazy linked lists | |
# we can however create lazy linked list using nested attribute sets, where the head is the node value and the tail is the nested cons | |
# we've basically created a recursive union type: | |
# type stream a = nil | { head = a; tail = stream a; } | |
# it's basically a lazy linked list!!!! | |
let | |
# O(n) access of the linked list, it needs to unwrap the linked list as it goes deeper into the list | |
streamElemAt = s: i: | |
if i == 0 | |
then s.head | |
else streamElemAt s.tail (i - 1); | |
# recursively creates a nested attribute set, with a head node and tail cell | |
fibsFrom = first: second: | |
{ | |
head = first; | |
tail = fibsFrom second (first + second); | |
}; | |
# wrapper function constructing a fibonnaci linked list with 1 and 1 as the first and second | |
fibs = fibsFrom 1 1; | |
in | |
streamElemAt fibs 30 | |
# ^--------- HOLY SHIT A LINKED LIST! A LAZY LINKED LIST!!! So now we can get any fibonnaci number just by using the fibs stream, this basically reifies the fibonnaci sequence, so you can now use it explicitly as a primitive object! |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment