Convert a list of digits to a number HASKELL

吃可爱长大的小学妹 提交于 2019-12-13 03:45:41

问题


I want to make a function in haskell that given a list of single digits, i make the full number. I was thinking in using intensive lists and patrons, as the code it follows:

funcion5 (x:xs) = [y*(10^w) | y <- (x:xs) w]

The idea is, to go over the list and multiplie each digit to 10 pow to the position of the number. Finally i only have to sum all digits and I have the number as this:

sum (funcion5 (x:xs))

Can anyone help me, please? Thanks


回答1:


This may simply be done by folding with foldl1 :: Foldable t => (a -> a -> a) -> t a -> a as follows;

Prelude> foldl1 (\x y -> 10*x+y) [1,2,3]
123



回答2:


You can use a "fold" pattern for this. We thus write this in terms of foldl :: (a -> b -> a) -> a -> [b] -> a:

function5 :: Num n => [n] -> n
function5 = foldl f 0
    where f a x = ...

So here f takes two parameters a (the thus far generated number), and x the next digit.

In a positional notation system, one can obtain the value by "scanning" left-to-right and each time multiplying the thus far obtained value with the radix, and adding the next digit. So this is the logic you need to "encode" in f: taking the thus far obtained value, and the next digit, and producing the next value.




回答3:


multiplos_10 = [10^x | x <- [0..]]
aux (x:xs) = sum ([a*b | (a,b) <- zip (x:xs) multiplos_10])
a_numero (x:xs) = aux (reverse(x:xs))


来源:https://stackoverflow.com/questions/53140675/convert-a-list-of-digits-to-a-number-haskell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!