How to resolve the algorithm Sum digits of an integer step by step in the Haskell programming language

Published on 7 June 2024 03:52 AM

How to resolve the algorithm Sum digits of an integer step by step in the Haskell programming language

Table of Contents

Problem Statement

Take a   Natural Number   in a given base and return the sum of its digits:

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Sum digits of an integer step by step in the Haskell programming language

This Haskell Program defines several functions for summing the digits of an integer in a given base, either represented as a string or an integer.

  • digsum is the first function and it accepts two Integral number arguments and returns their sum of digits in the given base. The function takes the base as the first argument and the number as the second argument. It uses a recursive helper function f that does the actual summation. The function stops when the number is 0, as there are no more digits to sum. If the number is not 0, the function divides the number by the base and recursively calls itself on the quotient and the remainder.

  • baseDigitSum is another function for summing the digits of an integer given as a string in a given base. The function takes two arguments, the base as the first argument and the number as the second argument. The function uses the unfoldr function from the Data.List module to generate a list of the digits of the number. It starts with the number, and for each iteration, it computes the quotient and remainder of the number divided by the base. The quotient is the next digit of the number, and the remainder is the new number. The process is repeated until the number is 0, at which point the list of digits is complete. The function then sums the list of digits using the foldr function.

  • digitSum is like the previous one but it sums the digits of a given string. It uses the digitToInt function from the Data.Char module to convert each character in the string to its corresponding digit. The function then uses the foldr function to sum the list of digits.

  • intDigitSum is different from the previous ones, it sums the digits of a given integer value in a given base. It does the same as the digitSum functions, but instead of taking a string, it takes an integer.

  • main is the main function of the program. It defines a list of tests for the digsum function, and for each test, it prints the base, the digits of the number, the value of the number, the sum of the digits of the number using the digsum function, and the sum of the digits of the number using the baseDigitSum function.

  • justifyRight is a utility function used to format the output of the main function. It takes a number of characters and a character as arguments, and it returns a function that takes a string and justify right-aligns it with the specified number of characters by prepending the specified character.

  • readBase is another utility function used to convert a string to an integer in a given base. It takes a base and a string as arguments, and it returns the integer value of the string in the given base.

  • showIntAtBase is also a utility function used to convert an integer to a string in a given base. It takes a base and an integer as arguments, and it returns a string representation of the integer in the given base.

Source code in the haskell programming language

digsum
  :: Integral a
  => a -> a -> a
digsum base = f 0
  where
    f a 0 = a
    f a n = f (a + r) q
      where
        (q, r) = n `quotRem` base

main :: IO ()
main = print $ digsum 16 255 -- "FF": 15 + 15 = 30


import Data.List (unfoldr)
import Data.Tuple (swap)

----------------- SUM DIGITS OF AN INTEGER ---------------

baseDigitSum :: Int -> Int -> Int
baseDigitSum base = sum . unfoldr go
  where
    go x
      | 0 < x = (Just . swap) $ quotRem x base
      | otherwise = Nothing

-------------------------- TESTS -------------------------
main :: IO ()
main =
  mapM_
    print
    [ baseDigitSum <$> [2, 8, 10, 16] <*> [255],
      baseDigitSum <$> [10] <*> [1, 1234],
      baseDigitSum <$> [16] <*> [0xfe, 0xf0e]
    ]


import Data.Char (digitToInt, intToDigit, isHexDigit)
import Data.List (transpose)
import Numeric (readInt, showIntAtBase)

------------------ SUM OF INTEGER DIGITS -----------------

digitSum :: String -> Int
digitSum = foldr ((+) . digitToInt) 0

intDigitSum :: Int -> Int -> Int
intDigitSum base =
  digitSum
    . flip (showIntAtBase base intToDigit) []


-------------------------- TESTS -------------------------
main :: IO ()
main =
  mapM_ putStrLn $
    unwords
      <$> transpose
        ( ( fmap
              =<< flip justifyRight ' '
                . succ
                . maximum
                . fmap length
          )
            <$> transpose
              ( [ "Base",
                  "Digits",
                  "Value",
                  "digit string -> sum",
                  "integer value -> sum"
                ] :
                ( ( \(s, b) ->
                      let v = readBase b s
                       in [ show b, -- base
                            show s, -- 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 = (drop . length) <*> (replicate n c <>)
    readBase b s = n
      where
        [(n, _)] = readInt b isHexDigit digitToInt s


  

You may also check:How to resolve the algorithm Kernighans large earthquake problem step by step in the JavaScript programming language
You may also check:How to resolve the algorithm Rock-paper-scissors step by step in the uBasic/4tH programming language
You may also check:How to resolve the algorithm Price fraction step by step in the RPL programming language
You may also check:How to resolve the algorithm Sorting algorithms/Heapsort step by step in the EchoLisp programming language
You may also check:How to resolve the algorithm Time a function step by step in the M2000 Interpreter programming language