2016-04-22 44 views
0
{- Define an employee type -} 
data Employee = Engineer {name :: String, engineerId :: String} 
       | Manager {name :: String, managerId :: Integer} 
       | Director {name :: String, directorId :: Integer} 
       deriving Show 

我定义了一个像下面这样的变量engineer1。如何在Haskell中获得数据构造函数的签名

*Main> let engineer1 = Engineer "Hari" "123" 

当我查询工程师1的类型时,它给了我像“工程师1 ::雇员”。我明白,工程师是数据构造函数,其中Employee是相应的类型构造函数。我的问题是,有没有什么办法可以像“Engineeer String String”:: Employee一样获得数据构造函数的签名。

回答

1

你可以创建这样一个功能:

typeEmployee :: Employee -> String 
typeEmployee (Engineer _ _) = "..." 
typeEmployee (Manager _ _) = "..." 
typeEmployee (Director _ _) = "..." 

其他选项,创建一个新类ShowType

-- TYPE 
data Employee a b = Engineer {name :: a, engineerId :: b} 
       | Manager {name :: a, managerId :: b} 
       | Director {name :: a, directorId :: b} 
       deriving Show 

-- CLASS 
class ShowType a where 
    showType :: a -> String 

-- INSTANCES 
instance ShowType Int where 
    showType _ = "Int" 

instance ShowType Integer where 
    showType _ = "Integer" 

instance ShowType Float where 
    showType _ = "Float" 

instance ShowType Char where 
    showType _ = "Char" 

instance (ShowType a) => ShowType [a] where 
    showType x = "[" ++ showType (head x) ++ "]" 

instance (ShowType a, ShowType b) => ShowType (Employee a b) where 
    showType (Engineer x y) = "Engineer " ++ showType x ++ ' ' : showType y 
    showType (Manager x y) = "Manager " ++ showType x ++ ' ' : showType y 
    showType (Director x y) = "Director " ++ showType x ++ ' ' : showType y 

现在,你可以这样做:

*Main> showType (Manager 12 "a") 
"Manager Integer [Char]" 

*Main> showType (Manager [56] 12) 
"Manager [Integer] Integer" 

*Main> let x = Engineer 12 5 :: (Employee Int Int) 
*Main> showType x 
"Engineer Int Int" 
+0

感谢您的回答。它解决了这个问题,有没有内置功能可以做到这一点?因为,对于具有类型变量的自定义类型,它很难管理。 –

+0

@HariKrishna no。 –

+0

再次检查我的答案。 @HariKrishna –

2
*Main> :t Engineer 
Engineer :: String -> String -> Employee 

请注意Employee是一种类型,而不是数据构造函数。

+0

通过查询像“ :t工程师“,我可以得到数据构造函数的特征。但我在寻找,如何通过查询变量'engineer1'itslef来得到这个。 –

+2

你必须编写一个'case'语句来找出它使用的数据构造函数,但是没有简单的方法从case语句的主体中获取某种类型的东西。 ':t'是一个ghci命令,而不是你可以在Haskell表达式中运行的东西。 –

相关问题