gpt4 book ai didi

haskell - 恢复 do 表示法语法

转载 作者:行者123 更新时间:2023-12-03 06:27:14 25 4
gpt4 key购买 nike

我正在阅读Scrap your type classes 。这为类型类提供了替代方案。然而,我被Paul Chiusano的评论所困扰。其中讨论了恢复 do 表示法 语法。

坦白说,我无法理解

return :: a -> (Monad f -> f a) 
(>>=) :: (Monad f -> f a) -> (a -> (Monad f -> f b)) -> (Monad f -> f b)

将有助于恢复do符号

You can implement all the monadic combinators like this, and desugar do notation to them. The do block evaluates to a function that accepts the monad dictionary, so you can even conveniently write code that's polymorphic in the choice of monad, without having to thread the dictionary around manually.

尤其是,它如何适应上面文章中提到的 GADT 风格方法的上下文?

最佳答案

{-# LANGUAGE Rank2Types, RebindableSyntax #-}

import qualified Prelude
import qualified System.IO
import Prelude (String, ($), (++))
import System.IO (IO)

根据加布里埃尔·冈萨雷斯的建议

data MonadI f = MonadI {
_return :: forall a . a -> f a,
_bind :: forall a b . f a -> (a -> f b) -> f b
}

您可以按如下方式实现必要的函数 return(>>=),并使用 Paul Chiusano 建议的类型:

return :: a -> (MonadI f -> f a)
return x = \dict -> (_return dict) x

(>>=) :: (MonadI f -> f a) -> (a -> (MonadI f -> f b)) -> (MonadI f -> f b)
ma >>= f = \dict -> (_bind dict) (ma dict) (\x -> f x dict)

这不足以恢复 do 符号,因为您还需要 (>>) 和 ( sadly ) fail。您可以按如下方式实现它们:

(>>) :: (MonadI f -> f a) -> (MonadI f -> f b) -> (MonadI f -> f b)
ma >> mb = ma >>= (\_ -> mb)

fail :: String -> MonadI f -> f a
fail str = \_ -> Prelude.error str -- Because let's not further entertain that idea.

现在我们拥有编写简单程序所需的工具:

main :: IO ()
main = (\m -> m monad'IO) $ do
putStrLn "What is your name?"
name <- getLine
putStrLn $ "Hello, " ++ name

当然,为此我们必须从 System.IO 借用一些东西:

getLine :: MonadI IO -> IO String
getLine = \_ -> System.IO.getLine

putStrLn :: String -> (MonadI IO -> IO ())
putStrLn str = \_ -> System.IO.putStrLn str

monad'IO :: MonadI IO
monad'IO = MonadI {
_return = (Prelude.return :: a -> IO a),
_bind = ((Prelude.>>=) :: IO a -> (a -> IO b) -> IO b)
}

关于haskell - 恢复 do 表示法语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33422437/

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