246

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?

4 Answers 4

344

The opposite of read is show.

Prelude> show 3
"3"

Prelude> read $ show 3 :: Int
3
Sign up to request clarification or add additional context in comments.

7 Comments

@Lega: You may find this useful: haskell.org/hoogle/?hoogle=Int+-%3E+String.
@ KennyTM A LOT of people will find that link useful! A link alone is +1, but for showing how to use it... That's +10 Thanks :)
Note that some organizations/standards strongly discourage the use of "show" because of its extreme polymorphism. A type-specific function (or, worst case, wrapper around show) would be helpful.
@JonWatte "Might", not "would". At the level of generality of this question, I don't think your suggestion is actionable.
Is there a way to do this manually without usyng system functions?
|
14

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)

2 Comments

More idiomatic for Haskell is putStrLn $ show x (using right-associative operator $)
@Arlind: As someone trying to learn Haskell I really appreciate an answer like this. I'm not trying to become a Haskell expert at this time. I'm just trying to get simple functions to work and show the results to the console. Later I can learn what is and isn't "idiomatic". Thanks for helping out a beginner :-)
7

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.

Comments

2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.