Haskell:将Int转换为String

时间:2010-05-06 20:32:22

标签: string haskell int casting

我知道您可以将String转换为read的数字:

Prelude> read "3" :: Int
3
Prelude> read "3" :: Double 
3.0

但是如何获取String值的Int表示?

4 个答案:

答案 0 :(得分:254)

read相反的是show

Prelude> show 3
"3"

Prelude> read $ show 3 :: Int
3

答案 1 :(得分:4)

基于Chuck的回答的例子:

myIntToStr :: Int -> String
myIntToStr x
    | x < 3     = show x ++ " is less than three"
    | otherwise = "normal"

请注意,如果没有show,第三行将无法编译。

答案 2 :(得分:2)

任何刚开始使用Haskell并尝试打印Int的人,请使用:

module Lib
    ( someFunc
    ) where

someFunc :: IO ()
x = 123
someFunc = putStrLn (show x)

答案 3 :(得分:0)

您可以使用显示:

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