242

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?

Chris Martin
  • 30,334
  • 10
  • 78
  • 137
Squirrelsama
  • 5,480
  • 4
  • 28
  • 38

4 Answers4

335

The opposite of read is show.

Prelude> show 3
"3"

Prelude> read $ show 3 :: Int
3
Chuck
  • 234,037
  • 30
  • 302
  • 389
  • 44
    @Lega: You may find this useful: http://www.haskell.org/hoogle/?hoogle=Int+-%3E+String. – kennytm May 06 '10 at 21:13
  • 4
    @ 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 :)** – CoR Jun 08 '12 at 22:23
  • 1
    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. – Jon Watte Mar 27 '15 at 16:34
  • @JonWatte "Might", not "would". At the level of generality of this question, I don't think your suggestion is actionable. – duplode Nov 21 '16 at 14:31
  • Is there a way to do this manually without usyng system functions? – lesolorzanov Feb 21 '17 at 07:51
  • @ZloySmiertniy: Of course. You just need to do the same things those functions do. There's no real magic to this function, just a bunch of logic. – Chuck Feb 21 '17 at 17:47
  • `readMaybe` or `readEither` are type safe and included in `base` under `Text.Read` ([Link](https://hackage.haskell.org/package/base-4.12.0.0/docs/Text-Read.html#v:readMaybe)). Included for reference. – Mikkel Apr 18 '20 at 18:05
13

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)
Arlind Hajredinaj
  • 8,380
  • 3
  • 30
  • 45
  • 1
    More idiomatic for Haskell is `putStrLn $ show x` (using right-associative operator $) –  Mar 28 '21 at 02:02
  • 2
    @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 :-) – devdanke Mar 30 '21 at 06:54
6

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.

prasad_
  • 12,755
  • 2
  • 24
  • 36
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

Willem van der Veen
  • 33,665
  • 16
  • 190
  • 155