Last active
December 15, 2015 08:48
-
-
Save DarrenN/5233153 to your computer and use it in GitHub Desktop.
Little Schemin' in CoffeeScript
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
car = (arr) -> | |
arr[0] | |
cdr = (arr) -> | |
arr[1..] | |
# Using for loop | |
map = (arr, func) -> | |
func(r) for r in arr | |
# Using recursion | |
_map = (arr, func, result) -> | |
result = result || [] | |
if arr.length == 0 | |
return result | |
result.push func car(arr) | |
_map cdr(arr), func, result | |
console.log map([1,2,3,4,5], (x) -> x * x) | |
console.log _map([1,2,3,4,5], (x) -> x * x) | |
# Using for loop | |
reduce = (arr, func, memo) -> | |
memo = func(val, memo) for val in arr | |
memo | |
# Using recursion | |
_reduce = (arr, func, memo) -> | |
n = car arr | |
unless n? | |
return memo | |
memo = func n, memo | |
_reduce cdr(arr), func, memo | |
f = (a,b) -> a * b | |
console.log _reduce([1,2,3,4,5], f, 3) | |
console.log reduce([1,2,3,4,5], f, 3) |
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
car = (arr) -> | |
arr[0] | |
cdr = (arr) -> | |
arr[1..] | |
# This doesn't really work the same way as cons in Scheme | |
cons = (a, b) -> | |
if a instanceof Array == false | |
a = [a] | |
if b.length == 0 | |
return a | |
a.push car(b) | |
cons a, cdr(b) | |
console.log cons(1, [2,3,4]) # [1,2,3,4] | |
rember = (a, list) -> | |
if list.length == 0 | |
return a | |
if car(list) == a | |
return cdr list | |
else | |
cons car(list), rember(a, cdr(list)) | |
console.log rember 'mint', ['lamb', 'chops', 'and', 'mint', 'flavored', 'mint', 'jelly'] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment