簡體   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