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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 00:44:22  来源:igfitidea点击:

Haskell: Converting Int to String

stringhaskellintcasting

提问by Squirrelsama

I know you can convert a Stringto an number with read:

我知道你可以将 a 转换String为一个数字read

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

But how do you grab the Stringrepresentation of an Intvalue?

但是你如何获取String一个Int值的表示呢?

回答by Chuck

The opposite of readis show.

的反义词readshow

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 showthe 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)