[英]Haskell: Converting Int to String
I know you can convert a String
to an number with read
:我知道您可以使用
read
将String
转换为数字:
Prelude> read "3" :: Int
3
Prelude> read "3" :: Double
3.0
But how do you grab the String
representation of an Int
value?但是如何获取
Int
值的String
表示呢?
The opposite of read
is show
. read
的反面是show
。
Prelude> show 3
"3"
Prelude> read $ show 3 :: Int
3
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)
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
,第三行将无法编译。
You can use show:您可以使用显示:
show 3
What I want to add is that the type signature of show is the following:我想补充的是,show 的类型签名如下:
show :: a -> String
And can turn lots of values into string not only type Int
.并且可以将大量值转换为字符串,而不仅仅是类型
Int
。
For example:例如:
show [1,2,3]
Here is a reference:这是一个参考:
https://hackage.haskell.org/package/base-4.14.1.0/docs/GHC-Show.html#v:show https://hackage.haskell.org/package/base-4.14.1.0/docs/GHC-Show.html#v:show
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.