且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

用Haskell将数字拆分为数字

更新时间:2022-11-14 15:50:55

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).