# How to put m balls in n boxes with each box having at least one ball

The calculation for the number of ways of putting $m$ balls in $n$ boxes with each box having at least one ball in Haskell:

fact 0 = 1 fact 1 = 1 fact x = x * fact (x - 1)     balls m 1 = 1 balls m n | m < n = 0 balls m n | m == n = fact(n) balls m n = n * balls (m -1) n + n * balls (m - 1) (n - 1)

Testing:

\$ ghci GHCi, version 7.6.3: http://www.haskell.org/ghc/ :? for help Loading package ghc-prim ... linking ... done. Loading package integer-gmp ... linking ... done. Loading package base ... linking ... done. Prelude>
Prelude> :l balls.hs [1 of 1] Compiling Main ( balls.hs, interpreted ) Ok, modules loaded: Main. *Main> balls 12 3 519156 *Main> balls 50 2 1125899906842622 *Main> balls 2 2 2 *Main> balls 3 2 6 *Main> balls 4 5 0 *Main> balls 5 10 0 *Main> balls 10 5 5103000 *Main> balls 10 2 1022 *Main> balls 10 9 16329600