Bool isEven x =-6ren">
gpt4 book ai didi

haskell - Haskell 的 "do"关键字有什么作用?

转载 作者:行者123 更新时间:2023-12-04 16:21:11 25 4
gpt4 key购买 nike

我是一名 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)

它的工作方式与我认为的完全一样。

这里发生了什么?为什么第一个代码片段不起作用?添加“做”实际上是做什么的?

PS。我在互联网上看到与“do”关键字相关的“monads”,这与此有关吗?

最佳答案

Why doesn't the first code snippet work?



do 之外 block ,换行符没有任何意义。所以你对 main 的第一个定义相当于 main = print (isEven 2) print (isOdd 2) ,失败是因为 print只接受一个论点。

现在你可能想知道为什么我们不能只使用换行符来表示一个函数应该被一个接一个地调用。问题在于 Haskell(通常)是惰性的并且纯粹是函数式的,因此函数没有副作用,并且没有一个接一个地调用函数的有意义的概念。

那么 print工作吗? print是一个接受字符串并产生 IO () 类型结果的函数. IO是一种表示可能产生副作用的操作的类型。 main生成此类型的值,然后将执行该值描述的操作。虽然没有一个接一个地调用函数的有意义的概念,但是一个接一个地执行一个 IO 值的操作是一个有意义的概念。为此,我们使用 >>运算符,它将两个 IO 值链接在一起。

I saw something about "monads" on the internet related to the "do" keyword, does that have something to do with this?



是的, Monad是一个类型类(如果你还不知道它们是什么:它们类似于 OO 语言中的接口(interface)),它(除其他外)提供函数 >>>>= . IO是该类型类的一个实例(在 OO 术语中:一种实现该接口(interface)的类型),它使用这些方法将多个操作链接在一起。
do语法是使用 >> 的更方便的方式和 >>= .具体来说,您对 main 的定义等同于以下没有 do :
main = (print (isEven 2)) >> (print (isOdd 2))

(额外的括号不是必需的,但我添加它们是为了避免混淆优先级。)

所以 main产生一个执行 print (isEven 2)步骤的IO值,其次是 print (isOdd 2) .

关于haskell - Haskell 的 "do"关键字有什么作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40832232/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com