以下是我的示例代码。据说工程师很特别,如果他的名字是“Hari”(或)id是13.我通过使用View Patterns来做到这一点。我可以在条件运算符上应用视图模式吗?
示例 如果他的id是< 50.
{-# LANGUAGE ViewPatterns #-}
module ABC where
type Name = String
type NoOfReportees = Integer
type EngineerId = Integer
type ManagerId = Integer
type DirectorId = Integer
{- Define an employee type -}
data Employee = Engineer Name EngineerId
| Manager Name [EngineerId] ManagerId
| Director Name [ManagerId] DirectorId
deriving Show
getEngineerFirstName :: Employee -> Name
getEngineerFirstName (Engineer name _) = name
getEngineerId :: Employee -> EngineerId
getEngineerId (Engineer _ empId) = empId
isSpecialEngineer :: Employee -> Bool
isSpecialEngineer (getEngineerFirstName -> "Hari") = True
isSpecialEngineer (getEngineerId -> 13) = True
isSpecialEngineer _ = False
答案 0 :(得分:5)
这有效
isSpecialEngineer (getEngineerId -> x) | x < 50 = True
但是,您必须完成getEngineerId函数才能返回每种类型员工的值。请注意,您也可以使用旧式模式在Engineer上进行模式匹配,并且更安全地执行此操作
isSpecialEngineer (Engineer _ x) | x < 50 = True