Last active
December 23, 2015 11:39
-
-
Save tonetheman/6630216 to your computer and use it in GitHub Desktop.
some lua testing a map function and a linked list, saw this in another lang on this site
http://www.braveclojure.com/core-functions-in-depth/
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
| local LL = {} -- class object | |
| function LL.new(val) | |
| local self = {} | |
| self.value = val | |
| self.next = nil | |
| function self:first() | |
| return self.value | |
| end | |
| function self:rest() | |
| return self.next | |
| end | |
| function self:cons(val) | |
| local tmp = LL.new(val) | |
| tmp.next = self | |
| return tmp | |
| end | |
| function self:repr() | |
| print(self.value) | |
| if self.next ~= nil then | |
| self.next:repr() | |
| end | |
| end | |
| return self | |
| end | |
| function mapp(list, f) | |
| if list == nil then | |
| return null | |
| else | |
| return list:cons( | |
| f(list:first()), -- call the function on the first item in the lits | |
| mapp(list:rest(), f)) -- call mapp on the rest of the list | |
| end | |
| end | |
| -- make a linked list node called head | |
| local head = LL.new(10) | |
| -- add a new node onto the front of the node | |
| head = head:cons(20) | |
| -- a function that will print a val if | |
| -- it comes in not nil | |
| function pp(val) | |
| if val ~= nil then | |
| io.write(string.format("val: %d\n", val)) | |
| end | |
| end | |
| -- call the mapp function | |
| mapp(head, pp) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment