在我写的错误单子上证明一些单子定律
所以我创建了一个自定义错误单子,我想知道如何为其证明一些单子定律。如果有人愿意花时间帮助我,我将不胜感激。谢谢!
这是我的代码:
data Error a = Ok a | Error String
instance Monad Error where
return = Ok
(>>=) = bindError
instance Show a => Show (Error a) where
show = showError
showError :: Show a => Error a -> String
showError x =
case x of
(Ok v) -> show v
(Error msg) -> show msg
bindError :: Error a -> (a -> Error b) -> Error b
bindError x f = case x of
(Ok v) -> f v
(Error msg) -> (Error msg)
So I whipped up a custom error monad and I was wondering how I would go about proving a few monad laws for it. If anyone is willing to take the time to help me out it would be much appreciated. Thanks!
And here's my code:
data Error a = Ok a | Error String
instance Monad Error where
return = Ok
(>>=) = bindError
instance Show a => Show (Error a) where
show = showError
showError :: Show a => Error a -> String
showError x =
case x of
(Ok v) -> show v
(Error msg) -> show msg
bindError :: Error a -> (a -> Error b) -> Error b
bindError x f = case x of
(Ok v) -> f v
(Error msg) -> (Error msg)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
首先陈述等式的一侧,然后尝试到达另一侧。我通常从“更复杂”的一侧开始,然后朝着更简单的一侧努力。对于第三定律,这是行不通的(双方都一样复杂),所以我通常从双方出发并尽可能地简化它们,直到达到相同的地方。然后我可以反转我从一侧采取的步骤来获得证明。
例如:
然后展开:
因此我们已经证明了
其他两个定律的过程大致相同。
Start by stating one side of the equation, and try to get to the other side. I usually start from the "more complicated" side and work toward the simpler one. For the third law this doesn't work (both sides are just as complex), so I usually go from both sides and simplify them as much as possible, until I get to the same place. Then I can just reverse the steps I took from one of the sides to get a proof.
So for example:
Then expand:
And thus we have proved
The process for the other two laws is approximately the same.
您的 monad 与
Either String a
同构(Right = Ok,Left = Error),我相信您已经正确实现了它。至于证明满足定律,我建议考虑当g
导致错误和h
导致错误时会发生什么。Your monad is isomorphic to
Either String a
(Right = Ok, Left = Error), and I believe you have implemented it correctly. As for proving the laws are satisfied, I recommend considering what happens wheng
results in an error, and whenh
results in an error.