Skip to content

Instantly share code, notes, and snippets.

@cutsea110
Last active April 12, 2020 07:54
Show Gist options
  • Save cutsea110/713e30adb1f3a683d2e48f7071a10299 to your computer and use it in GitHub Desktop.
Save cutsea110/713e30adb1f3a683d2e48f7071a10299 to your computer and use it in GitHub Desktop.
Subfactorial and exp
{-# LANGUAGE NPlusKPatterns #-}
{-# LANGUAGE LambdaCase #-}
module Subfactorial where
type Nat = Integer
foldn :: (a, a -> a) -> Nat -> a
foldn (c, f) = u
where u 0 = c
u (n+1) = f (u n)
paran :: (a, Nat -> a -> a) -> Nat -> a
paran (c, f) = u
where u 0 = c
u (n+1) = f (n+1) (u n)
-- >>> fact 9
-- 362880
fact = paran (1, (*))
-- >>> subfact 9
-- 133496
subfact = snd . paran (c, f)
where c = (0, 1)
f i (x, y) = (y, (i-1)*(x+y))
-- >>> e 9
-- 2.71828369389345
-- >>> e 20
-- 2.718281828459045
-- >>> exp 1
-- 2.718281828459045
e n = fromIntegral (fact n) / fromIntegral (subfact n)
test n = exp 1 == e n
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment