使用 Haskell 将数字拆分为数字 [英] Split a number into its digits with Haskell

查看:30
本文介绍了使用 Haskell 将数字拆分为数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一个任意数字,我如何单独处理该数字的每一位?

Given an arbitrary number, how can I process each digit of the number individually?

编辑我已经添加了一个基本的例子来说明 Foo 可能会做的事情.

Edit I've added a basic example of the kind of thing Foo might do.

例如,在 C# 中,我可能会这样做:

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);
}

推荐答案

您听说过 div 和模式?

如果您想首先处理最重要的数字,您可能需要反转数字列表.将数字转换为字符串是一种有缺陷的处理方式.

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

泛化为函数:

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 视为没有数字.如果您愿意,一个简单的包装函数可以处理这种特殊情况.

This treats 0 as having no digits. A simple wrapper function can deal with that special case if you want to.

请注意,此解决方案不适用于负数(输入 x 必须是整数,即整数).

Note that this solution does not work for negative numbers (the input x must be integral, i.e. a whole number).

这篇关于使用 Haskell 将数字拆分为数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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