寫給 stdout

根據 Haskell 2010 語言規範 ,以下是 Prelude 中可用的標準 IO 函式,因此不需要匯入它們。

putChar::Char -> IO () - 將 char 寫入 stdout

Prelude> putChar 'a'
aPrelude>  -- Note, no new line

putStr::String -> IO () - 將 String 寫入 stdout

Prelude> putStr "This is a string!"
This is a string!Prelude>  -- Note, no new line

putStrLn::String -> IO () - 將 String 寫入 stdout 並新增一個新行

Prelude> putStrLn "Hi there, this is another String!"
Hi there, this is another String!

print::Show a => a -> IO () - 將 a 的一個例項寫入 stdout

Prelude> print "hi"
"hi"
Prelude> print 1
1
Prelude> print 'a'
'a'
Prelude> print (Just 'a')  -- Maybe is an instance of the `Show` type class
Just 'a'
Prelude> print Nothing
Nothing

回想一下,你可以使用 deriving 為你自己的型別例項化 Show

-- In ex.hs
data Person = Person { name::String } deriving Show
main = print (Person "Alex")  -- Person is an instance of `Show`, thanks to `deriving`

在 GHCi 中載入和執行:

Prelude> :load ex.hs
[1 of 1] Compiling ex             ( ex.hs, interpreted )
Ok, modules loaded: ex.
*Main> main  -- from ex.hs
Person {name = "Alex"}
*Main>