Haskell从整数转换为字符串

Haskell从整数转换为字符串

本文介绍了Haskell从整数转换为字符串(自己的函数)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要函数帮助将整数转换为字符串:

I need help with my function to convert an integer into a string:

例如:fromInteger 19 =="91"

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'

这是我的主要功能:

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

推荐答案

首先,整数不是列表,因此您不能将整数传递给headtail.然后fromInteger已在前奏中定义,因此我建议将其重命名为fromInteger_.因此,要提取最低有效位,您可以将整数模10减少.但是,要应用撤消,还需要使用整数除以10可获得的前导位.有一个很好的函数divMod可以同时执行这两个操作一步.现在,建议的函数无法正常工作,因为它定义为返回String,但是第一种情况不返回字符串,因此让我们将其更改为空字符串"".然后,您想使用++连接字符串.这意味着我们需要将从fromDigit获得的数字转换为字符串-我们可以通过将其括在方括号中来实现. (字符串只不过是字符列表.)通过这些修改,一切似乎都可以正常工作:

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

尝试在线!

我不知道headtailnull会如何帮助您解决问题.

I don't see though how head and tail or null would help you with your approach.

这篇关于Haskell从整数转换为字符串(自己的函数)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 19:18