从GHCi使用RecordWildCards扩展时出错

时间:2017-06-02 19:24:12

标签: haskell record ghci

我创建了一个在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)’

1 个答案:

答案 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 ++ " "
相关问题