2016-04-22 67 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表達式中運行的東西。 –

相關問題