Haskell: Conversione da Int a String


198

So che puoi convertire un Stringin un numero con read:

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

Ma come afferrare la Stringrappresentazione di un Intvalore?

Risposte:


286

L'opposto di readè show.

Prelude> show 3
"3"

Prelude> read $ show 3 :: Int
3

38
@Lega: questo può essere utile: haskell.org/hoogle/?hoogle=Int+-%3E+String .
kennytm,

3
@ KennyTM MOLTE persone troveranno utile quel link! Un solo link è +1, ma per aver mostrato come usarlo ... Sono +10 Grazie :)
CoR

Si noti che alcune organizzazioni / standard scoraggiano fortemente l'uso dello "spettacolo" a causa del suo polimorfismo estremo. Una funzione specifica del tipo (o, nel peggiore dei casi, wrapper per show) sarebbe utile.
Jon Watte,

@JonWatte "Potrebbe", non "sarebbe". A livello di generalità di questa domanda, non credo che il tuo suggerimento sia attuabile.
duplode il

C'è un modo per farlo manualmente senza usare le funzioni di sistema?
lesolorzanov,

4

Un esempio basato sulla risposta di Chuck:

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

Si noti che senza la showterza riga non verrà compilato.


4

Chiunque abbia appena iniziato con Haskell e stia provando a stampare un Int, usa:

module Lib
    ( someFunc
    ) where

someFunc :: IO ()
x = 123
someFunc = putStrLn (show x)
Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.