问题
I need help with my function to convert an integer into a string:
for example: fromInteger 19 == "91"
My auxiliary-function to convert an integer into a character:
fromDigit :: Integer -> Char
fromDigit 0 = '0'
fromDigit 1 = '1'
fromDigit 2 = '2'
fromDigit 3 = '3'
fromDigit 4 = '4'
fromDigit 5 = '5'
fromDigit 6 = '6'
fromDigit 7 = '7'
fromDigit 8 = '8'
fromDigit 9 = '9'
This is my main function:
fromInteger :: Integer -> String
fromInteger n =
if n == 0 then ""
else fromInteger(tail n) ++ fromDigit(head n)
I should only use: tail, head, :, null and mathematical functions
回答1:
First of all, integers are not lists, so you cannot pass inteers to head
or tail
. Then fromInteger
is already defined in the prelude, so I'd recommend renaming it to fromInteger_
. So to extract the least significant digit, you can reduce the integer modulo 10. But to apply the recusion you also need the leading digits which you can get by using an integer division by 10. There is a nice function divMod
that does both in one step. Now your suggested function cannot work as you define it to return a String
but the first case does not return a string, so let's change that to a empty string ""
. Then you want to use ++
to concatenate strings. This means we need to conver the digit we get from fromDigit
to a string - and we can do that by enclosing it in a brackets. (Strings are nothing but lists of characters.) With these modification everything seems to work fine:
fromInteger_ :: Integer -> String
fromInteger_ n
| n == 0 = ""
| otherwise = fromInteger_ d ++ [fromDigit m]
where (d, m) = divMod n 10
main = print $ fromInteger_ 12451
Try it online!
I don't see though how head
and tail
or null
would help you with your approach.
回答2:
Make a simple function to get the digits in a list (in reverse order), using mod
and div
- or simply divMod
revDigs :: Integral a => a -> [a]
revDigs 0 = []
revDigs num = currDig : revDigs restDigs
where (restDigs, currDig) = num `divMod` 10
Now all you have to do, is map over your own fromDigit
function on the result of revDigs
.
Do note that there's a library function for this already - intToDigit. But I assume you cannot use that here.
So the final result would look like-
fromIntNum :: Integer -> [Char]
fromIntNum = map fromDigit . revDigs
来源:https://stackoverflow.com/questions/64766808/haskell-from-integer-into-a-string-own-function