Skip to content

Instantly share code, notes, and snippets.

@namelos
Created October 24, 2015 21:01
Show Gist options
  • Save namelos/f24374b8dddac4257ca3 to your computer and use it in GitHub Desktop.
Save namelos/f24374b8dddac4257ca3 to your computer and use it in GitHub Desktop.
some linked list functions
const n3 = { val: 3, nxt: null }
const n2 = { val: 2, nxt: n3 }
const n1 = { val: 1, nxt: n2 }
const fst = n => n.val
const rst = n => n.nxt
const cons = (val, n) => { val, nxt: n }
fst(n1) // 1
fst(rst(n1)) // 2
fst(rst(rst(n1))) // 3
const n0 = { val: 0, nxt: n1 }
fst(n0) // 0
fst(rst(n0)) // 1
// with a sequence which has fst rst and cons we could implement map
const map = (lst, trans) => list === null ? null :
cons(trans(fst(lst)), map(rst(lst), trans))
// impement sequence on array
const fst = arr => arr[0]
const slc = arr => arr.slice(1, arr.length)
const rst = arr => slc(arr).length === 0 ? null : slc(arr)
const cons = (val, arr) => [val].concat(arr)
const lst = [0, 1, 2]
const map(lst, x => x + 1) // [1, 2, 3]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment