Search code examples
haskellfunctional-programmingfactorialtype-mismatch

Haskell Implementation of Bell Numbers


I'm trying to implement a bell number finder + summation in Haskell. I'm fairly confident that my methods are correct, but I'm having problems with some errors at compile time. My current error message is:

[1 of 1] Compiling Main             ( survey2.hs, survey2.o )
survey2.hs:5:14:**
    Expected a constraint, but ‘Integer’ has kind ‘*’
    In the type signature for ‘binomial’:
      binomial :: (Integer, Integer) => Integer

survey2.hs:15:12:
    Expected a constraint, but ‘Integer’ has kind ‘*’
    In the type signature for ‘bellSum’: bellSum :: Integer => Integer**

I'm totally new to haskell and new to functional languages in general. Based on this error, I have tried changing my "function definitions" (Or whatever you call them in Haskell), but I just seem to cause more errors.

The end goal of the program is to print the sum of the bell numbers 0-9.

factorial n
  | n <= 1    = 1 
  | otherwise =  n * factorial(n-1)

binomial :: (Integer, Integer) => Integer
binomial n k 
  | k > n     = 0 
  | k < 0     = 0 
  | otherwise = factorial(n) / factorial(n-k) * factorial(k)

bell n
  | n <= 1    = 1 
  | otherwise = sum [ binomial (n-1, k-1)  * bell (k-1) | k<-[0..n-1] ] 

bellSum :: Integer => Integer  
bellSum n = sum [ bell(k) | k<-[0..n] ]

main = bell(9 :: Integer)

Solution

  • Note that this is not consistent (=> should be ->)

    binomial :: (Integer, Integer) -> Integer
    binomial n k 
    

    either change to

    binomial :: Integer -> Integer -> Integer
    binomial n k 
    

    or

    binomial :: (Integer, Integer) -> Integer
    binomial (n, k)
    

    Another hint for you, you can compute binomial without the factorial function (or even multiplication)

    binomial n k | k==0 || k==n = 1
                 | k==1 = n
                 | otherwise = binomial (n-1) (k-1) + binomial (n-1) k
    

    this is still very inefficient but it can be memoized.