Jump to content

Sum digits of an integer: Difference between revisions

m
Line 2,011:
{{Out}}
<pre>30</pre>
 
 
In terms of unfoldr:
<lang haskell>import Data.List (unfoldr)
import Data.Tuple (swap)
 
----------------- SUM DIGITS OF AN INTEGER ---------------
 
baseDigitSum :: Int -> Int -> Int
baseDigitSum base n = sum . unfoldr go
sum $where
unfoldr go x
| 0 < x then= (Just $. swap) $ quotRem x base
(\x ->
| otherwise if= 0 < xNothing
then Just $ swap $ quotRem x base
else Nothing)
n
 
-------------------------- TESTS -------------------------
main :: IO ()
main =
mapM_
print
[ baseDigitSum <$> [2, 8, 10, 16] <*> [255],
, baseDigitSum <$> [10] <*> [1, 1234],
, baseDigitSum <$> [16] <*> [0xfe, 0xf0e]
]</lang>
{{Out}}
9,655

edits

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