我如何获得Haskell中大数位数的总和? [英] How do I get the sums of the digits of a large number in Haskell?

查看:115
本文介绍了我如何获得Haskell中大数位数的总和?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一名C ++程序员,试图教授自己的Haskell,并且将握住使用函数作为循环类型的基础知识是具有挑战性的。我有一个很大的数字,50 !,我需要添加其数字的总和。这在C ++中是一个相对简单的循环,但我想学习如何在Haskell中完成它。

我已阅读了一些入门指南,能够获得50!

sum50fac.hs ::

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

不幸的是,在这一点上我不完全确定如何解决这个问题。
是否可以编写一个函数,将(mod)x 10加到某个值上,然后在x / 10上再次调用相同的函数,直到x / 10小于10?如果这是不可能的,我应该如何处理这个问题?



谢谢!

解决方案

为什么不只是

  sumd = sum。映射Char.digitToInt。显示


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!

解决方案

Why not just

sumd = sum . map Char.digitToInt . show

这篇关于我如何获得Haskell中大数位数的总和?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆