[英]How to convert Integer in String and String in Integer in Haskell?
我还在学习 Haskell 并且我真的对这种语言感到困惑......我必须实现两个函数fromInteger :: Integer -> String
和toInteger :: String -> Integer
通过数字字符串在 Haskell 整数和数字之间进行转换以相反的顺序,例如: "25" -> "52"
。 为了功能分解,我应该首先实现fromDigit :: Integer -> Char
和toDigit :: Char -> Integer
在数字和字符之间进行转换。 函数应该是什么样子的? 非常感谢!
您可以使用read :: Read a => String -> a
和show :: Show a => a -> String
从Integer
转换为String
:
Prelude> show 52
"52"
Prelude> read "52" :: Integer
52
但是您不需要将值转换为字符串来反转数字的顺序。 您可以使用递归和quotRem :: Integral a => a -> a -> (a, a)
来获得商和余数。
您还可以使用递归将Integer
转换为String
。 这里我们使用一个String
作为累加器,我们每次都计算最后一位。 这看起来像:
fromInteger :: Integer -> String
fromInteger = go []
where go ls x | x <= 9 = … : …
| otherwise = go (… : ls) …
where (q, r) = quotRem x 10
你仍然需要填写…
部分。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.