如何在Haskell中获取Data构造函数的签名

时间:2016-04-22 21:28:51

标签: haskell

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

我定义了一个变量engineer1,如下所示。

for f in try_files:
    print("trying %s"%f)
    s = subprocess.Popen("grep -r '%s' ../dir/*"%f)
    print(s)

当我查询engineer1的类型时,它给了我" engineer1 :: Employee"。我明白,Engineer是数据构造函数,其中Employee是对应的类型构造函数。我的问题是,有没有什么方法可以获得数据构造函数的签名,例如" Engineeer String String" ::员工。

2 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分: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"