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.
Last active
July 18, 2023 14:41
-
-
Save Bruno-366/f3eb4811ccbb919aeeedf93182d0bc48 to your computer and use it in GitHub Desktop.
Fibonacci in JavaScript - Concatenative-style
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 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] |
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 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] |
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
// 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