我创建了一个在Haskell记录类型上使用RecordWildCards
语法进行模式匹配的函数:
编译指示
我已将pragma放在文件的顶部。我也尝试使用: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
上使用此功能以使用PersonR
匹配as pattern
时,我得到:
功能
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)’
答案 0 :(得分:1)
你在这里的第一个案例中做得很好(虽然我修复了++
你+
的地方:
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 ++ " "