Last active
February 27, 2019 07:47
-
-
Save devmachiine/f67fa747a5a263bdde82536e3f861fbd to your computer and use it in GitHub Desktop.
Linked list in javascript, as a single fold function.
This file contains 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
// Aliases h=head, t=tail, f=function, z=zero (aka identity), n=node as right fold. | |
let n = (h,t) => (f,z) => | |
t ? f(h, t(f,z)) : f(h,z) | |
let p = console.log | |
let list = n(4, n(3, n(2, n(1)))) | |
let factorial4 = list((a,b) => a * b, 1) | |
p('!4 = ' + factorial4) | |
let add_no_zero = (a,b) => b ? a + b : a | |
p('Σ4 = ' + list(add_no_zero)) | |
let map = f => (h,t) => t ? n(f(h), t) : n(f(h)) | |
p('!14 / !10 = ' + list(map(x => x + 10))((a,b) => a * b, 1)) | |
// or just print to show order unchanged from map | |
p(list(map(x => x * 10))((a,b) => a + ' ' + b, 'oh')) | |
// ----------------------------------------------------------------------------------------------- | |
// curried version: | |
let n = h => t => z => f => | |
t ? f(t(z)(f))(h) : f(h)(z) | |
// uuu---g--llyy | |
let list = n(4)(n(3)(n(2)(n(1)()))) | |
let factorial4 = list(1)(a => b => a * b) | |
p(factorial4) | |
let addz = a => b => b ? a + b : a | |
p(list()(addz)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment