【发布时间】:2011-02-16 13:49:50
【问题描述】:
我知道你可以使用read 将String 转换为数字:
Prelude> read "3" :: Int
3
Prelude> read "3" :: Double
3.0
但是如何获取 Int 值的 String 表示形式?
【问题讨论】:
标签: string haskell int casting
我知道你可以使用read 将String 转换为数字:
Prelude> read "3" :: Int
3
Prelude> read "3" :: Double
3.0
但是如何获取 Int 值的 String 表示形式?
【问题讨论】:
标签: string haskell int casting
read 的反义词是show。
Prelude> show 3
"3"
Prelude> read $ show 3 :: Int
3
【讨论】:
任何刚开始使用 Haskell 并尝试打印 Int 的人,请使用:
module Lib
( someFunc
) where
someFunc :: IO ()
x = 123
someFunc = putStrLn (show x)
【讨论】:
putStrLn $ show x(使用右关联运算符 $)
一个基于 Chuck 回答的例子:
myIntToStr :: Int -> String
myIntToStr x
| x < 3 = show x ++ " is less than three"
| otherwise = "normal"
请注意,如果没有show,第三行将无法编译。
【讨论】:
你可以使用显示:
show 3
我要补充的是 show 的类型签名如下:
show :: a -> String
不仅可以输入Int,而且可以将很多值转换成字符串。
例如:
show [1,2,3]
这是一个参考:
https://hackage.haskell.org/package/base-4.14.1.0/docs/GHC-Show.html#v:show
【讨论】: