2

The recursive form is like that:

co:: (Int,Int) -> Int
co| k == 0 || k == n = 1
  | 0 < k, k < n = co(n-1,k-1) + co(n-1,k)
  | otherwise = 0

How do I memorize so I don't have to make the same calculations that often?

Rodrigo de Azevedo
  • 1,097
  • 9
  • 17
Anonnnn
  • 53
  • 2
  • 4
    Let's start by getting a solution that compiles and provides correct answers. You need to declare `n` and `k`. – Code-Apprentice Jan 25 '18 at 23:05
  • After you fix that, I think a more efficient solution comes directly from the definition: `nCk = n!/((k!)(n-k!))`. You can use `product` to calculate the factorials and then there is less need for memoization. – Code-Apprentice Jan 25 '18 at 23:08
  • 1
    You would store the values in a boxed data structure such as a map or array. Either update and insert each new value into the map, passing the updated map as program state, or use laziness to create a structure full of thunks, which will calculate the value once, only if needed. – Davislor Jan 25 '18 at 23:47

1 Answers1

2

Here’s how to implement binomial coefficients if you are feeling sane and want someone to understand your program:

--| computes the binomial coefficient n choose k = n!/k!(n-k)!
binom n k = product [max (k+1) (n-k+1) .. n] `div` product [1 .. min k (n-k)]

Here is a simple way to memoize a function of two arguments like this:

binom n k = (vals !! n) !! k where
  vals = 1 : [ 1 : [if k == n
                    then 1
                    else binom (n-1) (k-1) + binom (n-1) k
                   | k <- [1..n]]
             | n <- [1..]]
Dan Robertson
  • 4,315
  • 12
  • 17