首页 文章

Haskell列表理解中的非详尽模式[重复]

提问于
浏览
5

可能重复:当模式匹配失败时,为什么Haskell列表推导不会导致错误?

今天我看到了以下代码:

Prelude> [a | Just a <- [Just 10, Nothing, Just 20]]
[10, 20]

有用 . 但我认为上面的列表理解只是...的语法糖

[Just 10, Nothing, Just 20] >>= (\(Just x) -> return x)

...当遇到 Nothing 时,Haskell会发出错误 *** Exception: Non-exhaustive patterns in lambda .

所以我的问题是: [a | Just a <- [Just 10, Nothing, Just 20]] 转化为(就monadic代码而言)是否会忽略 Nothing

1 回答

  • 2

    我认为that other question中的最佳答案实际上是引用'compiler magic'的答案 . 您匹配模式 Just x ,并根据Haskell 2010 Report将行为指定为

    ..如果匹配失败,则简单地跳过列表中的该元素 .

    因此,我认为实施可以随意做到这一点(即,desugaring不一定是唯一的) .

相关问题