Raf*_*ael 3 haskell pattern-matching
当我浏览持久性源代码时,我在文件Quasi.hs中遇到了这个函数(我提到了一个标签,其相关代码等于master分支中当前状态的代码,因为标签的代码更不可能改变).在该行中takeConstraint ps tableName defs (n:rest) | not (T.null n) && isUpper (T.head n) = takeConstraint',参数模式后面有这个管道(|)字符.是的表达|和=类似的格局制约参数呢?那么我|在数学中将其解释为相同的符号,即"这样"吗?
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)
Run Code Online (Sandbox Code Playgroud)
是的,这恰恰意味着" 这样 ".这些是守卫,在Haskell中非常常见(通常优于等效if then else表达式).
f x
| x > 2 = a
| x < -4 = b
| otherwise = x
Run Code Online (Sandbox Code Playgroud)
相当于
f x = if x > 2 then a
else if x < -4 then b
else x
Run Code Online (Sandbox Code Playgroud)
国际海事组织,具体的例子实际上最好既if没有保护也没有保护,但是
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)
Run Code Online (Sandbox Code Playgroud)