gpt4 book ai didi

haskell - 在 monad 的上下文中是否一定要使用 do 符号?

转载 作者:行者123 更新时间:2023-12-02 14:48:45 25 4
gpt4 key购买 nike

Haskell 2010 年报告说

A do expression provides a more conventional syntax for monadic programming. It allows an expression such as

putStr "x: " >>
getLine >>= \l ->
return (words l)

to be written in a more traditional way as:

do putStr "x: "
l <- getLine
return (words l)

Thompson 说的 Haskell 函数式编程工艺

We'll continue to use the do notation, but will keep in mind that it essentially boils down to the existence of a function (>>=) which does the work of sequencing I/O programs, and binding their results for future use.

以上是否意味着在 monad 的上下文中必须使用 do 符号?

如果是,为什么下面的仿函数使用 do 表示法?

instance    Functor IO  where
-- fmap :: (a -> b) -> IO a -> IO b
fmap g mx = do {x <- mx; return (g x)}

最佳答案

是的。正如引用的文章所述,do -notation 只是 语法糖 用于 monad 操作。

这些是 the rules用于脱糖 do -符号:

  1. do {foobar; ...} = foobar >> do {...} (又名 foobar >>= \_ -> do {...})
  2. do {a <- foobar; ...} = foobar >>= \a -> do {...}
  3. do {foobar} = foobar

这必然意味着 do -notation 完全适用于 monad,除了规则 3 描述的微不足道的情况。

例如,如文章所述,do {putStr "x: "; l <- getLine; return (words l)}正好等于 putStr "x: " >> (getLine >>= \l -> return (words l)) ,您可以通过脱糖规则确认。

Functor IO 的定义中你在上面引用,Monad IO实例已经被定义,所以我们用它来定义 Functor实例也是。

注意到所有 monad 都必然是仿函数(参见 definition of the Monad typeclass)可能也很有用,所以当有人说 do 时-notation 适用于 monads,它也必然适用于仿函数。我怀疑这可能是一个混淆点。


值得注意的是,在某些受限情况下,可以仅使用 Applicative操作而不是更一般的Monad操作。例如,文章提供的示例可以写成 putStr "x: " *> (pure words <*> getLine) .有一个名为 ApplicativeDo 的实验性语言扩展这增加了 GHC 识别这些情况并概括 do 的某些情况的能力。 - 所有应用程序的符号,而不仅仅是所有单子(monad)。

关于haskell - 在 monad 的上下文中是否一定要使用 do 符号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57192516/

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