[英]Haskell IF Else
input <- readLn
if (input == 0)
then
putStr "0"
else if (input ==1)
then
putStr "1"
else if (input ==2)
在這種情況下,如何在then
或else if
中使用多個 putStr?
當我嘗試出錯時
Type error in application
*** Expression : putStr "0" putStr "0"
*** Term : putStr
*** Type : String -> IO ()
*** Does not match : a -> b -> c -> d
使用do
表示法:
do
a <- something
if a
then
do
cmd1
cmd2
else
do
cmd3
cmd4
cmd5 -- this comes after the 'then' and the 'else'
對此的規范解釋是,您想從兩個現有的一元值中形成一個新的一元值。 我們來看看 putStr 的類型,
IO ()
這意味着它是一個黑匣子,在執行時將“返回”單元類型的(唯一的)值。 一元計算背后的關鍵思想是你有一個組合器>>=
它將組合兩個一元表達式,將一個的結果輸入下一個(更准確地說,一個創建下一個的 function)。 一個關鍵點是IO
庫提供了這個組合器,這意味着,
IO
的情況下, RealWorld
state 包含打開的文件句柄等。在你的情況下,像這樣使用它,
putStr "0" >>= (\c -> putStr "0")
當然有捷徑
putStr "0" >> putStr "0"
還有 do-notation,正如另一張海報所提到的,它更像是語法糖,
do
putStr "0"
putStr "0"
對於這個人為的示例,您也可以使用一個案例,如下所示:
main = readLn >>= \input -> case input of
0 -> putStrLn "0"
1 -> putStrLn "0"
2 -> putStr "0"
>> putStrLn "0"
3 -> putStr "0"
>> putStr "0"
>> putStrLn "0"
_ -> putStrLn "infinite"
使用 do 語法可能更易於閱讀,但我想先不使用 do 語法來展示它,只是為了強調 do-syntax 只是語法,實際上並沒有做任何特別的事情。 這里是do-syntax。
main = do
input <- readLn
case input of
0 -> putStrLn "0"
1 -> putStrLn "0"
2 -> do putStr "0"
putStrLn "0"
3 -> do putStr "0"
putStr "0"
putStrLn "0"
_ -> putStrLn "infinite"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.