2016-04-22 5 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 

私は以下のように可変エンジニア1を定義しました。Haskellでデータコンストラクタのシグニチャを取得する方法

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

私はengineer1のタイプを照会すると「engineer1 :: Employee」のようになります。エンジニアはデータコンストラクタです。従業員は対応する型コンストラクタです。私の質問は、 "Engineeer String String" :: Employeeのようなデータコンストラクタのシグネチャを得ることができる方法があるかどうかです。

答えて

1

次のような機能を作成することができます。 "

*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

答えをありがとう。それは問題を解決する、これを行うinbuilt関数はありますか?型変数を持つカスタム型の場合は、管理が難しいためです。 –

+0

@HariKrishna no。 –

+0

私の答えをもう一度チェックしてください。 @ハリクリシュナ –

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

Employeeは、データコンストラクタではないタイプであることに注意してください。

+0

をのような照会することにより:今

-- 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 

、あなたが行うことができます。新しいクラスShowTypeを作成し、

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

その他のオプション:tエンジニア "、私はデータコンストラクタのシンセを得ることができます。しかし、私は探しています、どのように変数 'エンジニア1' itslefを照会することでこれを取得する。 –

+2

どのデータコンストラクタを使用したのか把握するためには 'case'文を書く必要がありますが、case文の内部から何かの型を取得するのは簡単ではありません。 ':t'は、Haskellの式の中で実行できるものではなく、ghciコマンドです。 –