我是一名C++/Java程序員,我正在努力學習Haskell(以及一般的函數式編程),並且我一直在努力。有一兩件事我想是這樣的:Haskell的「do」關鍵字有什麼作用?
isEven :: Int -> Bool
isEven x =
if mod x 2 == 0 then True
else False
isOdd :: Int -> Bool
isOdd x =
not (isEven x)
main =
print (isEven 2)
print (isOdd 2)
但是在編譯期間這個失敗,此錯誤:
ghc --make doubler.hs -o Main
[1 of 1] Compiling Main (doubler.hs, doubler.o)
doubler.hs:11:5: error:
• Couldn't match expected type ‘(a0 -> IO()) -> Bool -> t’
with actual type ‘IO()’
• The function ‘print’ is applied to three arguments,
but its type ‘Bool -> IO()’ has only one
In the expression: print (isEven 2) print (isOdd 2)
In an equation for ‘main’: main = print (isEven 2) print (isOdd 2)
• Relevant bindings include main :: t (bound at doubler.hs:10:1)
make: *** [all] Error 1
於是,我看到了一些代碼,在網上與「做」的關鍵字,所以我想它像這樣:
isEven :: Int -> Bool
isEven x =
if mod x 2 == 0 then True
else False
isOdd :: Int -> Bool
isOdd x =
not (isEven x)
main = do
print (isEven 2)
print (isOdd 2)
它的工作原理和我以爲應該完全一樣。
這是怎麼回事?爲什麼第一個代碼片段不起作用?添加「做」實際上是做什麼的?
PS。我在互聯網上看到有關「do」關鍵字的「單子」,這是否與此有關?
我覺得這個問題太寬泛了,你最好去閱讀一本haskell書中的'Monad'章節。您可以通過在本網站或Google上搜索「desugaring do notation haskell」來回答您的問題,但您可能需要更多背景信息 – jberryman
['do' notation](https://en.wikibooks.org/wiki/ Haskell/do_notation)是普通一元代碼的糖。如果沒有'do',你可以寫'main = print(isEven 2)>> print(isOdd 2)'。 – Alec