[英]Haskell: Constraining function pattern variables with |
While I was browsing Persistent source code, I came across this function below in file Quasi.hs (I referred to a tag with the relevant code equal to the one in the present state in master branch, since the tag's code is more unlikely to change). 当我浏览持久性源代码时,我在文件Quasi.hs中遇到了这个函数(我提到了一个标签,其相关代码等于master分支中当前状态的代码,因为标签的代码更不可能改变)。 In the line
takeConstraint ps tableName defs (n:rest) | not (T.null n) && isUpper (T.head n) = takeConstraint'
在行
takeConstraint ps tableName defs (n:rest) | not (T.null n) && isUpper (T.head n) = takeConstraint'
takeConstraint ps tableName defs (n:rest) | not (T.null n) && isUpper (T.head n) = takeConstraint'
there is this pipe (|) character following the argument pattern. takeConstraint ps tableName defs (n:rest) | not (T.null n) && isUpper (T.head n) = takeConstraint'
参数模式后面有这个管道(|)字符。 Is the expression between |
是
|
之间的表达式 and =
like a constraint to arguments in the pattern? 和
=
喜欢模式中参数的约束? So do I interpret this |
所以我解释这个
|
as the same symbol in Math, ie "such that" ? 在数学中作为相同的符号,即“这样” ?
takeConstraint :: PersistSettings
-> Text
-> [FieldDef]
-> [Text]
-> (Maybe FieldDef, Maybe CompositeDef, Maybe UniqueDef, Maybe UnboundForeignDef)
takeConstraint ps tableName defs (n:rest) | not (T.null n) && isUpper (T.head n) = takeConstraint' --- <<<<< This line
where
takeConstraint'
| n == "Unique" = (Nothing, Nothing, Just $ takeUniq ps tableName defs rest, Nothing)
| n == "Foreign" = (Nothing, Nothing, Nothing, Just $ takeForeign ps tableName defs rest)
| n == "Primary" = (Nothing, Just $ takeComposite defs rest, Nothing, Nothing)
| n == "Id" = (Just $ takeId ps tableName (n:rest), Nothing, Nothing, Nothing)
| otherwise = (Nothing, Nothing, Just $ takeUniq ps "" defs (n:rest), Nothing) -- retain compatibility with original unique constraint
takeConstraint _ _ _ _ = (Nothing, Nothing, Nothing, Nothing)
Yes, it means precisely “ such that ”. 是的,这恰恰意味着“ 这样 ”。 These are guards , very common in Haskell (generally preferred to the equivalent
if
then
else
expression). 这些防护装置 ,在Haskell很常见的(通常优选为等效
if
then
else
表达式)。
f x
| x > 2 = a
| x < -4 = b
| otherwise = x
is equivalent to 相当于
f x = if x > 2 then a
else if x < -4 then b
else x
IMO that specific example would actually have better been written with neither if
nor guards, but 国际海事组织,具体的例子实际上最好用
if
和guard来写,但是
takeConstraint' = case n of
"Unique" -> (Nothing, Nothing, Just $ takeUniq ps tableName defs rest, Nothing)
"Foreign" -> (Nothing, Nothing, Nothing, Just $ takeForeign ps tableName defs rest)
"Primary" -> (Nothing, Just $ takeComposite defs rest, Nothing, Nothing)
"Id" -> (Just $ takeId ps tableName (n:rest), Nothing, Nothing, Nothing)
_ -> (Nothing, Nothing, Just $ takeUniq ps "" defs (n:rest), Nothing)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.