Jump to content

Sum digits of an integer: Difference between revisions

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, intersperse)
import Numeric (showIntAtBasereadInt, readIntshowIntAtBase)
 
------------------ SUM OF INTEGER DIGITS -----------------
 
digitSum :: String -> Int
Line 2,050 ⟶ 2,052:
 
intDigitSum :: Int -> Int -> Int
intDigitSum base n = digitSum (showIntAtBase base intToDigit n [])
digitSum
. flip (showIntAtBase base intToDigit) []
 
 
-- TESTS -------------------------- TESTS -------------------------
main :: IO ()
main =
mapM_ putStrLn $
unwords
unwords <$>
<$> transpose
( ( fmap
((fmap =<< flip justifyRight ' ' . succ . maximum . fmap length) <$>
=<< flip justifyRight ' '
transpose
([ "Base" . succ
, "Digits" . maximum
, "Value" . fmap length
, "digit string -> sum")
, "integer value - <$> sum"transpose
] : ( [ "Base",
((\(s, b) -> "Digits",
let v = readBase b s"Value",
in [ show b "digit string --> basesum",
, show s"integer value --> digitssum"
,] show v -- value:
,( show( \(digitSums, sb) -- sum from digit string>
, show (intDigitSum b v) -- sumlet fromv base= andreadBase b values
]) <$> in [ show b, -- base
[("1", 10), ("1234", 10), ("fe", 16), ("f0e" show s, 16)])))-- digits
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 s = (drop (. length s) <*> (replicate n c ++ s<>)
readBase b s = n
where
let [(n, _)] = readInt b isHexDigit digitToInt s
in [(n, _)] = readInt b isHexDigit digitToInt s</lang>
{{Out}}
<pre> Base Digits Value digit string -> sum integer value -> sum
9,655

edits

Cookies help us deliver our services. By using our services, you agree to our use of cookies.