Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format Float as Int when printing in Haskell

This Haskell program prints "1.0" How can I get it to print "1"?

fact 0 = 1
fact x = x * fact (x-1)

place m n = (fact m) / (fact n) * (fact (m-n))

main = do   
   print (place 0 0)
like image 281
Richard Hayes Avatar asked Sep 01 '16 14:09

Richard Hayes


1 Answers

By using the / operation, you are asking haskell to use a fractional data type. You probably don't want that in this case. It is preferable to use an integral type such as Int or Integer. So I suggest to do the following: 1. Add a type declaration for the fact function, something like fact :: Integer -> Integer 2. Use quot instead of /.

So your code should look like this:

fact :: Integer -> Integer
fact 0 = 1
fact x = x * fact (x-1)

place :: Integer -> Integer -> Integer
place m n = (fact m) `quot` (fact n) * (fact (m-n))

main = do   
   print (place 0 0)

Also, as @leftaroundabout pointed out, you probably want to use a better algorithm for computing those binomial numbers.

like image 120
redneb Avatar answered Sep 28 '22 17:09

redneb