Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the sums of the digits of a large number in Haskell?

Tags:

haskell

I'm a C++ Programmer trying to teach myself Haskell and it's proving to be challenging grasping the basics of using functions as a type of loop. I have a large number, 50!, and I need to add the sum of its digits. It's a relatively easy loop in C++ but I want to learn how to do it in Haskell.

I've read some introductory guides and am able to get 50! with

sum50fac.hs::

fac 0 = 1
fac n = n * fac (n-1)
x = fac 50
main = print x

Unfortunately at this point I'm not entirely sure how to approach the problem. Is it possible to write a function that adds (mod) x 10 to a value and then calls the same function again on x / 10 until x / 10 is less than 10? If that's not possible how should I approach this problem?

Thanks!

like image 273
Tim Avatar asked May 15 '10 02:05

Tim


People also ask

What is integral Haskell?

Haskell has two integral types, namely Int and Integer . Int is the type of limited-precision integers; this means that there is a smallest integer of type Int , namely minBound , and a greatest integer of type Int , namely maxBound .


1 Answers

sumd 0 = 0
sumd x = (x `mod` 10) + sumd (x `div` 10)

Then run it:

ghci> sumd 2345
14

UPDATE 1:

This one doesn't generate thunks and uses accumulator:

sumd2 0 acc = acc
sumd2 x acc = sumd2 (x `div` 10) (acc + (x `mod` 10))

Test:

ghci> sumd2 2345 0
14

UPDATE 2:

Partially applied version in pointfree style:

sumd2w = (flip sumd2) 0

Test:

ghci> sumd2w 2345
14

I used flip here because function for some reason (probably due to GHC design) didn't work with accumulator as a first parameter.

like image 129
YasirA Avatar answered Oct 07 '22 14:10

YasirA