gpt4 book ai didi

haskell - 保护语法中的逗号有什么作用?

转载 作者:行者123 更新时间:2023-12-03 09:11:24 25 4
gpt4 key购买 nike

在我正在阅读的代码库中,我发现了这样的函数声明(缺少某些部分):

filepathNormalise :: BS.ByteString -> BS.ByteString
filepathNormalise xs
| isWindows, Just (a,xs) <- BS.uncons xs, sep a, Just (b,_) <- BS.uncons xs, sep b
= '/' `BS.cons` f xs

逗号在这里有什么作用?

(仅作为奖励,如果有人很容易知道这一点:Haskell Programming 中是否从第一原则中提到了这种语法,如果是,在哪里?因为我不记得读过它。)

最佳答案

Haskell 2010 section 3.13, Case Expressions 中描述了守卫。
(该部分是关于 case 表达式,而不是顶级声明,但大概语义是相同的):

guards  →  | guard1, …, guardn      (n ≥ 1)
guardpat <- infixexp (pattern guard)
| let decls (local declaration)
| infixexp (boolean guard)

For each guarded expression, the comma-separated guards are tried sequentially from left to right. If all of them succeed, then the corresponding expression is evaluated in the environment extended with the bindings introduced by the guards. That is, the bindings that are introduced by a guard (either by using a let clause or a pattern guard) are in scope in the following guards and the corresponding expression. If any of the guards fail, then this guarded expression fails and the next guarded expression is tried.



在简单的情况下,逗号的作用类似于 bool 和。但是逗号更强大,因为每个守卫都可以引入新的绑定(bind),供后续守卫使用(从左到右进行)。

守卫中的逗号并不常见(至少根据我的经验),我将这个功能描述为 Haskell 琐事——对于编写(或者,在大多数情况下,阅读)Haskell 完全没有必要。我怀疑 Haskell Programming 从第一原则中忽略了它。

关于haskell - 保护语法中的逗号有什么作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46509876/

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