Haskell: Converting Int to String

StringHaskellIntCasting

String Problem Overview


I know you can convert a String to an number with 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 Solutions


Solution 1 - String

The opposite of read is show.

Prelude> show 3
"3"

Prelude> read $ show 3 :: Int
3

Solution 2 - String

Anyone who is just starting with Haskell and trying to print an Int, use:

module Lib
    ( someFunc
    ) where

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

Solution 3 - String

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.

Solution 4 - String

You can use show:

show 3

What I want to add is that the type signature of show is the following:

show :: a -> String

And can turn lots of values into string not only type 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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSquirrelsamaView Question on Stackoverflow
Solution 1 - StringChuckView Answer on Stackoverflow
Solution 2 - StringArlindView Answer on Stackoverflow
Solution 3 - Stringprasad_View Answer on Stackoverflow
Solution 4 - StringWillem van der VeenView Answer on Stackoverflow