【问题标题】:How to convert Integer in String and String in Integer in Haskell?如何在 Haskell 中转换 Integer in String 和 String in Integer?
【发布时间】:2021-02-21 17:44:03
【问题描述】:

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

【问题讨论】:

  • 请不要将这些函数命名为fromIntegertoInteger,它们已经是不兼容的标准函数的名称了。
  • 但是在我的练习中是这样命名的,我必须这样写。

标签: string haskell char integer digits


【解决方案1】:

您可以使用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

您仍然需要填写 部分。

【讨论】:

  • 谢谢!我只能使用++、null、head和tail。
  • @Anastasia: 和模式匹配:)。你可以通过递归和模式匹配来实现reverse
猜你喜欢
  • 2019-05-05
  • 2019-12-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-18
  • 1970-01-01
  • 1970-01-01
  • 2021-11-09
相关资源
最近更新 更多