Skip to content

Instantly share code, notes, and snippets.

@Bruno-366
Last active July 18, 2023 14:41
Show Gist options
  • Save Bruno-366/f3eb4811ccbb919aeeedf93182d0bc48 to your computer and use it in GitHub Desktop.
Save Bruno-366/f3eb4811ccbb919aeeedf93182d0bc48 to your computer and use it in GitHub Desktop.
Fibonacci in JavaScript - Concatenative-style

Fibonacci Sequence in Javascript - Concatenative-style

Demo on how to produce the Fibonacci Sequence in Javascript - Concatenative-style.
Drawing inspiration from Concatenative Programming Languages, such as Forth and Factor,
this demonstration relies on recursion or iteration only for ease-of-use rather than functionality.

const fib = ([a,b,...c]) => [a+b,a,b,...c]
fib([1,0]) // --> [1,1,0]
fib(fib(fib([1,0]))) // --> [3,2,1,1,0]
const repeat = (n, f, a) => {
console.log(n,f,a)
let x = f(a); // store returned value of applying args to function
return (n - 1) == 0 ? x // if we are at zero return x
: repeat(n - 1, f, x) ; // else repeat again, this time decreasing counter by one
}
repeat(3,fib,[1,0]) // --> [3,2,1,1,0]
// I'm 98% sure that the repeat above is tail call optimized,
// but most Javascript engines don't perform TCO,
// so here is an iterative version:
const repeat_iter = (n, f, a) => {
let x = a
for (let i = n; i > 0; i--) {
x = f(x)
}
return x
}
repeat_iter(3,fib,[1,0]) // --> [3,2,1,1,0]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment