Last active
May 18, 2017 18:19
-
-
Save SerpentChris/ac5a6ed2acd3d2f43872d1dcd907f637 to your computer and use it in GitHub Desktop.
A LISP inspired linked list in Javascript
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
const nil = {} | |
function isNil(p){ | |
return p === nil | |
} | |
function makePair(a, b){ | |
return {head: a, tail: b} | |
} | |
function head(p){ | |
return p.head | |
} | |
function tail(p){ | |
return p.tail | |
} | |
function array_to_list(args){ | |
if(args.length === 0) | |
return nil | |
else | |
return makePair(args[0], array_to_list(args.slice(1))) | |
} | |
function append(list, val){ | |
if(isNil(list)) | |
return makePair(val, nil) | |
else | |
return makePair(head(list), append(tail(list), val)) | |
} | |
function remove(list, val){ | |
if(isNil(list)) | |
return nil | |
else if(head(list) === val) | |
return tail(list) | |
else | |
return makePair(head(list), remove(tail(list), val)) | |
} | |
function list_to_string(list){ | |
function helper(lst, string){ | |
if(isNil(lst)) | |
return string + ')' | |
else if(isNil(tail(lst))) | |
return string + head(lst) + ')' | |
else | |
return helper(tail(lst), string + head(lst) + ' ') | |
} | |
return helper(list, '(') | |
} | |
function map(func, list){ | |
if(isNil(list)) | |
return nil | |
else | |
return makePair(func(head(list)), map(func, tail(list))) | |
} | |
function accumulate(func, list, initial){ | |
if(isNil(list)) | |
return initial | |
else | |
return accumulate(func, tail(list), func(initial, head(list))) | |
} | |
function square(x){ | |
return x*x | |
} | |
function sum(a, b){ | |
return a + b | |
} | |
function test(){ | |
var x = [1,2,3] | |
console.log(x) | |
x = array_to_list(x) | |
console.log(x) | |
console.log(list_to_string(x)) | |
x = remove(x, 2) | |
console.log(list_to_string(x)) | |
x = append(x, 5) | |
console.log(list_to_string(x)) | |
x = map(square, x) | |
console.log(list_to_string(x)) | |
console.log(accumulate(sum, x, 0)) | |
} | |
test() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment