用Haskell将数字拆分为数字 [英] Split a number into its digits with Haskell
问题描述
给定一个任意数字,我该如何处理数字的每个数字?
编辑
我已添加例如,在C#中,我可能会做类似于 Foo
类型的事情。
static void Main(string [] args)
{
int number = 1234567890;
string numberAsString = number.ToString();
foreach(char x in numberAsString)
{
string y = x.ToString();
int z = int.Parse(y);
Foo(z);
void Foo(int n)
{
Console.WriteLine(n * n);
}
href =http://www.haskell.org/tutorial/numbers.html =noreferrer> div和mod ?
如果你想首先处理最重要的数字,你可能会想要颠倒数字列表。
135`div` 10 = 13
135 `mod` 10 = 5
概括为一个函数:
digs :: Integral x => x - > [x]
digs 0 = []
digs x = digs(x`div` 10)++ [x`mod` 10]
或者相反:
digs :: Integral x => ; x - > [x]
digs 0 = []
digs x = x`mod` 10:digs(x`div` 10)
这将 0
视为没有数字。一个简单的包装函数可以处理这种特殊情况,如果你想要。
请注意,这种解决方案不适用于负数(输入 x
必须是整数,即整数。)
Given an arbitrary number, how can I process each digit of the number individually?
Edit
I've added a basic example of the kind of thing Foo
might do.
For example, in C# I might do something like this:
static void Main(string[] args)
{
int number = 1234567890;
string numberAsString = number.ToString();
foreach(char x in numberAsString)
{
string y = x.ToString();
int z = int.Parse(y);
Foo(z);
}
}
void Foo(int n)
{
Console.WriteLine(n*n);
}
Have you heard of div and mod?
You'll probably want to reverse the list of numbers if you want to treat the most significant digit first. Converting the number into a string is an impaired way of doing things.
135 `div` 10 = 13
135 `mod` 10 = 5
Generalize into a function:
digs :: Integral x => x -> [x]
digs 0 = []
digs x = digs (x `div` 10) ++ [x `mod` 10]
Or in reverse:
digs :: Integral x => x -> [x]
digs 0 = []
digs x = x `mod` 10 : digs (x `div` 10)
This treats 0
as having no digits. A simple wrapper function can deal with that special case if you want to.
Note that this solution does not work for negative numbers (the input x
must be integral, i.e. a whole number).
这篇关于用Haskell将数字拆分为数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!