使用GHCI的RecordWildCards扩展时出错



我创建了一个函数,该函数使用 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 ++ " "

最新更新