ฉันรู้ว่าคุณสามารถแปลงเป็นStringตัวเลขด้วยread:
Prelude> read "3" :: Int
3
Prelude> read "3" :: Double
3.0
แต่คุณจะนำStringเสนอIntคุณค่าได้อย่างไร
ฉันรู้ว่าคุณสามารถแปลงเป็นStringตัวเลขด้วยread:
Prelude> read "3" :: Int
3
Prelude> read "3" :: Double
3.0
แต่คุณจะนำStringเสนอIntคุณค่าได้อย่างไร
คำตอบ:
ตรงข้ามคือreadshow
Prelude> show 3
"3"
Prelude> read $ show 3 :: Int
3
ตัวอย่างตามคำตอบของ Chuck:
myIntToStr :: Int -> String
myIntToStr x
| x < 3 = show x ++ " is less than three"
| otherwise = "normal"
โปรดทราบว่าหากไม่มีshowบรรทัดที่สามจะไม่รวบรวม
ทุกคนที่เพิ่งเริ่มต้นด้วย Haskell และพยายามพิมพ์ Int ให้ใช้:
module Lib
( someFunc
) where
someFunc :: IO ()
x = 123
someFunc = putStrLn (show x)