I want to write a bernoulli function bernoulli:: Integer -> Rational
in haskell, using the following algorithm for calculating the bernoulli number for a given integer.
the functions "frac" and "binom" are used to calculate the binomial in the definition. this is what i have so far:
fact :: Integer -> Integer
fact i = foldr (*) 1 [1..i]
binom :: Integer -> Integer -> Integer
binom n k = (fact n) `div` (fact k* fact (n-k))
bernoulli :: Integer -> Rational
bernoulli 0 = 1
bernoulli i = ((binom i j) * (bernoulli j)) / (j - i - 1) where j = i-1
I've tried it a few different times now, but either the recursion doesn't work or the resulting Rational is wrong.
I found three problems in your code:
binom
Rational
andInteger
bernoulli
is not a sum, but only first memberIn my code, you can see how I coped with these problems.
Test:
Output:
Small addition:
If we don't follow the rule of leveraging existing libraries, the solution could also look like this:
Because:

Note the similarity of the program with mathematical notation.
p.s.
bernoulli
withfoldr
: