且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Haskell从整数转换为字符串(自己的函数)

更新时间:2023-02-03 08:55:12

首先,整数不是列表,因此您不能将整数传递给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.