将整数列表转换为haskell中的一个Int(如concat) [英] Convert list of Integers into one Int (like concat) in haskell

查看:167
本文介绍了将整数列表转换为haskell中的一个Int(如concat)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

标题说的很多。我有一个整数列表,如下所示:[1,2,3]。我想把它改为Integer 123.我的第一个想法是concat,但是这不起作用,因为它是错误的类型,我尝试了各种各样的东西,但通常我只是返回相同的列表。任何帮助非常感谢。



另外我还找到了一种方法来打印正确的东西(putStr),除了我想要的类型是Integer和putStr不会这样做。

解决方案

您可以使用 foldl 将所有列表元素:

  fromDigits = foldl addDigit 0 
其中addDigit num d = 10 * num + d

addDigit 函数由<$ c $调用c> foldl 从最左边的一个开始依次添加数字。

  *主> fromDigits [1,2,3] 
123

编辑:

foldl 从左至右遍历列表,添加元素以累积一些值。



在这种情况下, foldl 0 的第二个参数是过程的起始值。在第一步中,通过调用 addDigit 0 1 将该起始值与 1 (列表的第一个元素)组合在一起>。这导致10 * 0 + 1 = 1。在下一步中,这个1与列表的第二个元素相结合,由 addDigit 1 2 ,给出10 * 1 + 2 = 12.然后这与列表的第三个元素相结合,由 addDigit 12 3 ,导致10 * 12 + 3 = 123。



因此,毫无意义地乘以零仅仅是第一步,在下面的步骤中,实际需要乘法将新数字添加到累计数字的末尾。 b $ b

Pretty much what the title says. I have a list of Integers like so: [1,2,3]. I want to change this in to the Integer 123. My first thought was concat but that doesn't work because it's of the wrong type, I've tried various things but usually I just end up returning the same list. Any help greatly appreciated.

Also I have found a way to print the right thing (putStr) except I want the type to be Integer and putStr doesn't do that.

解决方案

You can use foldl to combine all the elements of a list:

fromDigits = foldl addDigit 0
   where addDigit num d = 10*num + d

The addDigit function is called by foldl to add the digits, one after another, starting from the leftmost one.

*Main> fromDigits [1,2,3]
123

Edit:
foldl walks through the list from left to right, adding the elements to accumulate some value.

The second argument of foldl, 0 in this case, is the starting value of the process. In the first step, that starting value is combined with 1, the first element of the list, by calling addDigit 0 1. This results in 10*0+1 = 1. In the next step this 1 is combined with the second element of the list, by addDigit 1 2, giving 10*1+2 = 12. Then this is combined with the third element of the list, by addDigit 12 3, resulting in 10*12+3 = 123.

So pointlessly multiplying by zero is just the first step, in the following steps the multiplication is actually needed to add the new digits "to the end" of the number getting accumulated.

这篇关于将整数列表转换为haskell中的一个Int(如concat)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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