Skip to content

Instantly share code, notes, and snippets.

@igrep
Last active July 30, 2019 04:04
Show Gist options
  • Save igrep/afcf4789d88da3b3995308e2e12c59df to your computer and use it in GitHub Desktop.
Save igrep/afcf4789d88da3b3995308e2e12c59df to your computer and use it in GitHub Desktop.
Roughly simulate the difference between pointfree style and pointful style. Inspired by https://kakkun61.hatenablog.com/entry/2019/07/29/%E9%96%A2%E6%95%B0%E3%81%AE%E3%83%A1%E3%83%A2%E5%8C%96
/*
fact :: Int -> Integer
fact 0 = 1
fact n = fromIntegral n * fact (n-1)
*/
const fact = function(n){
if (n == 0){
return 1;
} else {
return n * fact(n - 1);
}
};
/*
fact3 :: Int -> Integer
fact3 = (map fact [0..] !!)
where
fact 0 = 1
fact n = fromIntegral n * fact (n-1)
*/
const fact3 = function(){
// Up to 1000 because infinite list is hard to express in JavaScript
const facts3 = [...Array(1000).keys()].map((n) => fact(n));
return function(n){
return fact3[n];
};
};
/*
fact4 :: Int -> Integer
fact4 x = map fact' [0..] !! x
where
fact' 0 = 1
fact' n = fromIntegral n * fact' (n-1)
*/
const fact4 = function(){
return function(n){
// Up to 1000 because infinite list is hard to express in JavaScript
const facts4 = [...Array(1000).keys()].map((n) => fact(n));
return fact4[n];
};
};
@igrep
Copy link
Author

igrep commented Jul 30, 2019

Unfortunately, I failed to compare the performance difference between fact3 and fact4.
Because JavaScript's Number gets overflown easily (I should rewrite with BigInt, but cumbersome!), and JavaScript's stack size is too small.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment