Last active
July 30, 2019 04:04
-
-
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
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
/* | |
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]; | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Unfortunately, I failed to compare the performance difference between
fact3
andfact4
.Because JavaScript's
Number
gets overflown easily (I should rewrite withBigInt
, but cumbersome!), and JavaScript's stack size is too small.