I'm new to Haskell
and I came into the code below and don't actually understand what it does. I know that the toDigits
function is declared to take an Integer
and return an array of Integer
s. If the argument n
equals 0 or less, we return an empty array, otherwise...? That's the mystery!
toDigits :: Integer -> [Integer]
toDigits n
| n < 1 = []
| otherwise = reverse $ split [] n
where split _ 0 = []
split acc m = lastDigit m : split acc (dropLastDigit m)
Could you please explain to me?
reverse $ split [] n
Is the same as
reverse (split [] n)
It reverses the return value of split [] n
and returns the result.
Split is defined in the next line.
It takes a list (an accumulator) and an Integer and does this:
Note that I assume that split is defined as follows (current implementation does not use acc). I also assume lastDigit
and dropLastDigit
do as their names would suggest:
split acc 0 = acc
split acc m = split (lastDigit m : acc) (dropLastDigit m)
Now, split returns acc if m is zero, otherwise it recursively prepends last digit of m to acc and pass it as the first argument to split , and removes the last digit from m and pass it as the second argument to split . In other words, this function eventually splits a number to its digits and returns the result as a list of Integers. Having this said calling split [] 1234
would return [1, 2, 3, 4]
. You probably don't need to reverse the result of calling split.
Here, it takes a number and builds a list of its digits, one by one. At each moment it first checks whether the number argument is zero (then the returned value is an empty list), and, if not, a) takes its last digit; b) prepends the digit to the result of a recursive call to itself, now with number with the last digit dropped. The acc argument is never actually used, since the recursion was finally settled to be modulo cons.
Note that list is finally built in least-endian order: the first element to the list is the least significant digit of the number.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.