Haskell:用|来约束函数模式变量

时间:2017-03-27 15:59:37

标签: 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)

1 个答案:

答案 0 :(得分:6)

是的,这意味着“这样”。这些是guards,在Haskell中非常常见(通常优先于等效的if then else表达式。

f x
 | x > 2      = a
 | x < -4     = b
 | otherwise  = x

相当于

f x = if x > 2 then a
               else if x < -4 then b
                              else x

国际海事组织,具体的例子实际上最好不是用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)