求教等式为啥成立

2022-05-26 14:22:04 +08:00
 eote
newtype Parser a = Parser (String -> [(a, String)])

apply :: Parser a -> String -> [(a, String)]
apply (Parser p) s = p s

instance Monad Parser where 
 return x = Parser (\s -> [(x, s)])
 p >>= q  = Parser (\s -> [(y, s'') | (x, s') <- apply p s, (y, s'') <- apply (q x) s'])


fail = Parser (\s -> [])

guard :: Bool -> Parser ()
guard True  = return ()
guard False = fail


sat :: (Char -> Bool) -> Parser Char
sat p = do { c <- getc; guard (p c); return c }


-- 以上是背景
-- 以下是问题

-- 为啥 guard (p c) >> return c = fail >> return c = fail
-- p c == True 很好理解 guard (p c)结果被弃掉了
-- p c == False 为啥没走到 return c
1135 次点击
所在节点    编程
3 条回复
iamzuoxinyu
2022-05-26 14:57:41 +08:00
eote
2022-05-26 15:20:16 +08:00
@iamzuoxinyu url 说的是 pattern failure 吧
leomayleomay
2022-05-27 05:29:21 +08:00
Prelude 里面的 guard 貌似需要 context 是 Alternative https://hackage.haskell.org/package/base-4.16.1.0/docs/Control-Monad.html#v:guard

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/855433

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX