Sum digits of an integer: Difference between revisions
→{{header|Haskell}}
Line 2,043:
Or, we could write '''sum . fmap digitToInt''', or the equivalent but more efficient fusion of it to a single fold: '''foldr ((+) . digitToInt) 0'''
<lang haskell>import Data.Char (digitToInt, intToDigit, isHexDigit)
import Data.List (transpose
import Numeric (
------------------ SUM OF INTEGER DIGITS -----------------
digitSum :: String -> Int
Line 2,050 ⟶ 2,052:
intDigitSum :: Int -> Int -> Int
intDigitSum base
digitSum
. flip (showIntAtBase base intToDigit) []
main :: IO ()
main =
mapM_ putStrLn $
unwords
<$> transpose
( ( fmap
=<< flip justifyRight ' '
show v, -- value
-- sum from digit string
show (digitSum s),
-- sum from base and value
show (intDigitSum b v)
]
)
<$> [ ("1", 10),
("1234", 10),
("fe", 16),
("f0e", 16)
]
)
)
)
where
justifyRight n c
readBase b s = n
where
{{Out}}
<pre> Base Digits Value digit string -> sum integer value -> sum
|