我创建了一个函数,该函数使用 RecordWildCards
语法在Haskell记录类型上进行模式匹配:
PRAGMAS
我将布拉格马斯放在文件的顶部。我还尝试使用:set -XRecordWildCards
添加它。
{-# LANGUAGE ViewPatterns #-}
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE RecordWildCards #-}
键入定义
data ClientR = GovOrgR { clientRName :: String }
| CompanyR { clientRName :: String,
companyId :: Integer,
person :: PersonR,
duty :: String
}
| IndividualR { person :: PersonR }
deriving Show
data PersonR = PersonR {
firstName :: String,
lastName :: String
} deriving Show
功能
greet2 :: ClientR -> String
greet2 IndividualR { person = PersonR { .. } } = "hi" ++ firstName ++ " " ++ lastName + " "
greet2 CompanyR { .. } = "hello " ++ firstName ++ " " ++ lastName ++ "who works as a " ++ duty ++ " " ++ clientRName + " "
greet2 GovOrgR {} = "Welcome"
错误
• Couldn't match expected type ‘[Char]’
with actual type ‘PersonR -> String’
• Probable cause: ‘lastName’ is applied to too few arguments
In the first argument of ‘(++)’, namely ‘lastName’
In the second argument of ‘(++)’, namely
‘lastName ++ "who works as a " ++ duty ++ " " ++ clientRName + " "’
In the second argument of ‘(++)’, namely
‘" "
++
lastName ++ "who works as a " ++ duty ++ " " ++ clientRName + " "’
Failed, modules loaded: none.
当我在CompanyR
上使用此功能以使用as pattern
匹配PersonR
时,我得到:
功能
greet2 c@(CompanyR { .. }) = "hello " ++ (firstName $ person c) ++ " " ++ (lastName $ person c)
错误
Couldn't match expected type ‘ClientR -> PersonR’
with actual type ‘PersonR’
• The function ‘person’ is applied to one argument,
but its type ‘PersonR’ has none
In the second argument of ‘($)’, namely ‘person c’
In the first argument of ‘(++)’, namely ‘(firstName $ person c)’
• Couldn't match expected type ‘ClientR -> PersonR’
with actual type ‘PersonR’
• The function ‘person’ is applied to one argument,
but its type ‘PersonR’ has none
In the second argument of ‘($)’, namely ‘person c’
In the second argument of ‘(++)’, namely ‘(lastName $ person c)’
在您的第一种情况下,您可以在此处进行(尽管我在 +
的情况下修复了 ++
(:
greet2 :: ClientR -> String
greet2 IndividualR { person = PersonR { .. } } = "hi" ++ firstName ++ " " ++ lastName ++ " "
但这里的firstName
等不是CompanyR
中的记录,因此CompanyR { .. }
不会将它们带入范围:
greet2 CompanyR { .. } = "hello " ++ firstName ++ " " ++ lastName ++ "who works as a " ++ duty ++ " " ++ clientRName + " "
您必须像在greet2
的第一种情况下一样做:
greet2 CompanyR {person = PersonR { .. }, .. } = "hello " ++ firstName ++ " " ++ lastName ++ "who works as a " ++ duty ++ " " ++ clientRName ++ " "