Last active
August 29, 2015 14:16
-
-
Save fuzzyalej/cf3870103cd28206f780 to your computer and use it in GitHub Desktop.
Functional JS Workshop
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
| function cell(value) { | |
| return { | |
| value: value, | |
| next: null //null is cool | |
| }; | |
| } | |
| function cons(value, list) { | |
| var tmp = cell(value); | |
| tmp.next = list || null; | |
| return tmp; | |
| } | |
| function list() { | |
| if(arguments[0] === undefined) return null; | |
| var args = Array.prototype.slice.call(arguments), | |
| head = args[0], | |
| tail = args.slice(1); | |
| return cons(head, list.apply(this, tail)); | |
| } | |
| function first(list) { | |
| if(list === null) return null; | |
| return list.value; | |
| } | |
| var car = first; | |
| var head = first; | |
| function rest(list) { | |
| if(list === null) return null; | |
| return list.next; | |
| } | |
| var cdr = rest; | |
| var tail = rest; | |
| function last(list) { | |
| if(rest(list) === null) return first(list); | |
| return last(rest(list)); | |
| } | |
| function length(list) { | |
| if(list === null) return 0; | |
| return 1 + length(rest(list)); | |
| } | |
| function replace_first(value, list) { | |
| return cons(value, rest(list)); | |
| } | |
| function nth(position, list) { | |
| if(position > length(list) || position < 1) return null; | |
| if(position === 1) return first(list); | |
| return nth(position-1, rest(list)); | |
| } | |
| function print(list) { | |
| if(list === null) return ''; | |
| return ('' + first(list) + ' ' + print(rest(list))); | |
| } |
partition!
function partition(list, fn) { return cons(filter(list, fn), list(unfilter(list, fn))); }
any!
function any(list, fn) { if(fn(first(list))) return true; return any(rest(list), fn); }
or
function any(list, fn) { return length(filter(list, fn)) >= 1; }
Author
from @kanedaki:
function every(list, fn) {
if (list === null) {return true}
if (!fn(first(list))) {return false}
return every(rest(list));
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
partition!
function partition(fn, list) {
return cons(cell(filter(list, fn)), cell(filter(list, function(e) {return !fn(e)}));
}