繁体   English   中英

如何在 Haskell 中转换字符串中的整数和整数中的字符串?

[英]How to convert Integer in String and String in Integer in Haskell?

我还在学习 Haskell 并且我真的对这种语言感到困惑......我必须实现两个函数fromInteger :: Integer -> StringtoInteger :: String -> Integer通过数字字符串在 Haskell 整数和数字之间进行转换以相反的顺序,例如: "25" -> "52" 为了功能分解,我应该首先实现fromDigit :: Integer -> ChartoDigit :: Char -> Integer在数字和字符之间进行转换。 函数应该是什么样子的? 非常感谢!

您可以使用read :: Read a => String -> ashow :: Show a => a -> StringInteger转换为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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM