我是一名C++/Java程序员,现在正试着学习Haskell(和函数式编程),但感觉进展不顺。我尝试了以下的方法:
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
我在网上看到一些带有“do”关键字的代码,所以我尝试了以下这样写:
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)
它的运行方式与我预期的完全一样。
这里发生了什么?为什么第一个代码片段不起作用?添加“do”实际上是做什么的?
顺便说一下,我在互联网上看到了与“do”关键字相关的“单子”,这与此有关吗?
do
表达式是常见单子代码的语法糖。没有do
,可以这样写:main = print (isEven 2) >> print (isOdd 2)
。 - Alec