Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const N = 10
- // sum natural numbers from 1 to n
- const sumNat = n => n * (n + 1) / 2
- console.log(`sumNat(${N}) = ${sumNat(N)}`)
- // implement iteratively
- const sumNat1 = n => {
- let count = 0
- for (let i = 1; i <= n; i++) count += i
- return count
- }
- console.log(`sumNat1(${N}) = ${sumNat1(N)}`)
- // implement exact algorithm recursively
- const sumNat2 = (n, i = 1, count = 0) =>
- i <= n ? sumNat2(n, i + 1, count + i) : count
- console.log(`sumNat2(${N}) = ${sumNat2(N)}`)
- // recurse from n to 1 instead of 1 to n
- const sumNat3 = (n, count = 0) =>
- n ? sumNat3(n - 1, count + n) : count
- console.log(`sumNat3(${N}) = ${sumNat3(N)}`)
- // recurse then add instead of add then recurse
- const sumNat4 = n => n ? sumNat4(n - 1) + n : 0
- console.log(`sumNat4(${N}) = ${sumNat4(N)}`)
- // generate array from 1 to n with ugly hack
- const range = n => [...Array(n).keys()].map(i => i + 1)
- // add all the things
- const sum1 = ns => ns.reduce((count, n) => count + n)
- console.log(`sum1(range(${N})) = ${sum1(range(N))}`)
- // create reusable function
- const add_ = (x, y) => x + y
- const sum2 = ns => ns.reduce(add_)
- console.log(`sum2(range(${N})) = ${sum2(range(N))}`)
- // curry all the things
- const reduce = combine => init => xs => {
- const uncurry = f => (x, y) => f(x)(y)
- return xs.reduce(uncurry(combine), init)
- }
- const add = x => (y => x + y)
- // sum = ns => helper(ns) is just sum = helper
- const sum3 = /* ns => */ reduce(add)(0)/* (ns) */
- console.log(`sum3(range(${N})) = ${sum3(range(N))}`)
- // multiply all the things
- const mult = x => y => x * y
- const prod1 = reduce(mult)(1)
- // calculate the factorial
- console.log(`prod1(range(${N})) = ${prod1(range(N))}`)
- // generalize the pattern
- const combineAll = ({combine, makeInit}) => {
- const init = makeInit()
- return reduce(combine)(init)
- }
- // implement addition
- const addMonoid = { combine: add, makeInit: () => 0 }
- const sum4 = combineAll(addMonoid)
- console.log(`sum4(range(${N})) = ${sum4(range(N))}`)
- // implement multiplication
- const multMonoid = { combine: mult, makeInit: () => 1 }
- const prod2 = combineAll(multMonoid)
- console.log(`prod2(range(${N})) = ${prod2(range(N))}`)
- // implement concatenation
- const concat = xs => ys => [...xs, ...ys]
- const concatMonoid = { combine: concat, makeInit: () => [] }
- const flatten = combineAll(concatMonoid)
- const nestedArrays = [range(3), range(2), range(1)]
- console.log(`flatten(${
- JSON.stringify(nestedArrays)}) = ${
- JSON.stringify(flatten(nestedArrays))}`)
- /*
- * Tex recommends:
- * - drboolean.gitbooks.io/mostly-adequate-guide-old
- * - sanctuary.js.org
- * - gcanti.github.io/fp-ts
- * - reasonml.github.io
- */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement