Haskell:将 Int 转换为 String
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2784271/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Haskell: Converting Int to String
提问by Squirrelsama
I know you can convert a String
to an number with read
:
我知道你可以将 a 转换String
为一个数字read
:
Prelude> read "3" :: Int
3
Prelude> read "3" :: Double
3.0
But how do you grab the String
representation of an Int
value?
但是你如何获取String
一个Int
值的表示呢?
回答by Chuck
The opposite of read
is show
.
的反义词read
是show
。
Prelude> show 3
"3"
Prelude> read $ show 3 :: Int
3
回答by prasad_
An example based on Chuck's answer:
一个基于查克回答的例子:
myIntToStr :: Int -> String
myIntToStr x
| x < 3 = show x ++ " is less than three"
| otherwise = "normal"
Note that without the show
the third line will not compile.
请注意,没有show
第三行将无法编译。
回答by Arlind
Anyone who is just starting with Haskell and trying to print an Int, use:
任何刚开始使用 Haskell 并尝试打印 Int 的人,请使用:
module Lib
( someFunc
) where
someFunc :: IO ()
x = 123
someFunc = putStrLn (show x)