Sum digits of an integer: Difference between revisions
Content added Content deleted
Line 2,011: | Line 2,011: | ||
{{Out}} |
{{Out}} |
||
<pre>30</pre> |
<pre>30</pre> |
||
In terms of unfoldr: |
In terms of unfoldr: |
||
<lang haskell>import Data.List (unfoldr) |
<lang haskell>import Data.List (unfoldr) |
||
import Data.Tuple (swap) |
import Data.Tuple (swap) |
||
----------------- SUM DIGITS OF AN INTEGER --------------- |
|||
baseDigitSum :: Int -> Int -> Int |
baseDigitSum :: Int -> Int -> Int |
||
baseDigitSum base |
baseDigitSum base = sum . unfoldr go |
||
where |
|||
go x |
|||
⚫ | |||
(\x -> |
|||
| otherwise = Nothing |
|||
⚫ | |||
else Nothing) |
|||
n |
|||
-------------------------- TESTS ------------------------- |
|||
main :: IO () |
main :: IO () |
||
main = |
main = |
||
mapM_ |
mapM_ |
||
print |
print |
||
[ baseDigitSum <$> [2, 8, 10, 16] <*> [255] |
[ baseDigitSum <$> [2, 8, 10, 16] <*> [255], |
||
baseDigitSum <$> [10] <*> [1, 1234], |
|||
baseDigitSum <$> [16] <*> [0xfe, 0xf0e] |
|||
]</lang> |
]</lang> |
||
{{Out}} |
{{Out}} |