gpt4 book ai didi

haskell - 这个 State monad 代码是如何工作的?

转载 作者:行者123 更新时间:2023-12-02 02:51:49 26 4
gpt4 key购买 nike

此代码来自 article

在这部分之前,我一直能够关注它。

module Test where

type State = Int

data ST a = S (State -> (a, State))

apply :: ST a -> State -> (a,State)
apply (S f) x = f x

fresh = S (\n -> (n, n+1))

instance Monad ST where
-- return :: a -> ST a
return x = S (\s -> (x,s))

-- (>>=) :: ST a -> (a -> ST b) -> ST b
st >>= f = S (\s -> let (x,s') = apply st s in apply (f x) s')

data Tree a = Leaf a | Node (Tree a) (Tree a) deriving (Show)


mlabel :: Tree a -> ST (Tree (a,Int))
-- THIS IS THE PART I DON'T UNDERSTAND:
mlabel (Leaf x) = do n <- fresh
return (Leaf (x,n))
mlabel (Node l r) = do l' <- mlabel l
r' <- mlabel r
return (Node l' r')

label t = fst (apply (mlabel t) 0)

tree = Node (Node (Leaf 'a') (Leaf 'b')) (Leaf 'c')

label tree产生:
Node (Node (Leaf ('a',0)) (Leaf ('b',1))) (Leaf ('c',2))

我可以看到 >>=运算符是“链接”返回单子(monad)(或类似的东西)的函数的工具。

虽然我认为我理解这段代码,但我不明白这段特定代码是如何工作的。

具体 do n <- fresh .我们还没有向fresh传递任何论据,对吧? n <- fresh 是什么意思在那种情况下产生?完全不明白这一点。也许它与 curry 有关?

最佳答案

Specifically do n <- fresh. We haven't passed any argument to fresh, right?



确切地。我们正在写一个将传递给 fresh 的参数。例如,当我们执行 apply (mlabel someTree) 5 之类的操作时.一个很好的练习可以帮助你更清楚地看到正在发生的事情是先写 mlabel。显式 (>>=)而不是 do-notation,然后替换 (>>=)return用什么 Monad实例说他们是。

关于haskell - 这个 State monad 代码是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31506839/

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