質問

代数 データ型 (adts)haskellのインスタンスは自動的にいくつかになります Typeclasses(次のように Show, Eq) に 派生 彼らから。

data  Maybe a  =  Nothing | Just a
  deriving (Eq, Ord)

私の質問は、これはどうですか deriving 作業、つまり、Haskellは、派生ADTの派生タイプクラスの機能を実装する方法をどのように知っていますか?

また、なぜそうです deriving 特定のタイプクラスのみに制限されていますか?導き出すことができる自分のタイプクラスを書くことができないのはなぜですか?

役に立ちましたか?

解決

短い答えは、魔法です:-)。これは、自動導入がHaskell仕様に焼き付けられていると言うことであり、すべてのコンパイラが独自の方法でそれを実装することを選択できます。ただし、拡張可能にする方法については、多くの作業があります。

派生する Haskellが独自の派生メカニズムを書くことができるツールです。

GHCは、派生可能なタイプのクラス拡張機能を提供するために使用されました 一般的なクラス, 、しかし、やや弱かったので、それはめったに使用されませんでした。これは現在取り出されており、このペーパーで説明されているように、新しい汎用派生メカニズムを統合する作業が進行中です。 http://www.dreixel.net/research/pdf/gdmh.pdf

これの詳細については、参照してください。

他のヒント

Haskell 98レポートから:

派生インスタンスが許可されているプレリュードの唯一のクラスは、EQ、ORD、列挙、境界、表示、および読み取りです...

これらのタイプクラスを導き出す方法の説明は次のとおりです。 http://www.haskell.org/onlinereport/derived.html#derived-appendix

使用することができます テンプレートhaskell 派生クロースと同様の方法でインスタンス宣言を生成します。

次の例は、恥知らずに盗まれています Haskell wiki:

この例では、次のHaskellコードを使用します

$(gen_render ''Body)

次のインスタンスを作成するには:

instance TH_Render Body where
  render (NormalB exp) = build 'normalB exp
  render (GuardedB guards) = build 'guardedB  guards

関数 gen_render 上記は次のように定義されています。 (このコードは、上記の使用法とは別のモジュールにある必要があることに注意してください)。

-- Generate an intance of the class TH_Render for the type typName
gen_render :: Name -> Q [Dec]
gen_render typName =
  do (TyConI d) <- reify typName -- Get all the information on the type
     (type_name,_,_,constructors) <- typeInfo (return d) -- extract name and constructors                  
     i_dec <- gen_instance (mkName "TH_Render") (conT type_name) constructors
                      -- generation function for method "render"
                      [(mkName "render", gen_render)]
     return [i_dec]  -- return the instance declaration
             -- function to generation the function body for a particular function
             -- and constructor
       where gen_render (conName, components) vars 
                 -- function name is based on constructor name  
               = let funcName = makeName $ unCapalize $ nameBase conName 
                 -- choose the correct builder function
                     headFunc = case vars of
                                     [] -> "func_out"
                                     otherwise -> "build" 
                      -- build 'funcName parm1 parm2 parm3 ...
                   in appsE $ (varE $ mkName headFunc):funcName:vars -- put it all together
             -- equivalent to 'funcStr where funcStr CONTAINS the name to be returned
             makeName funcStr = (appE (varE (mkName "mkName")) (litE $ StringL funcStr))

次の機能とタイプを使用します。

最初に、コードをより読みやすくするためのいくつかのタイプの同義語。

type Constructor = (Name, [(Maybe Name, Type)]) -- the list of constructors
type Cons_vars = [ExpQ] -- A list of variables that bind in the constructor
type Function_body = ExpQ 
type Gen_func = Constructor -> Cons_vars -> Function_body
type Func_name = Name   -- The name of the instance function we will be creating
-- For each function in the instance we provide a generator function
-- to generate the function body (the body is generated for each constructor)
type Funcs = [(Func_name, Gen_func)]

主な再利用可能な関数。インスタンスの関数を生成するために、関数のリストを渡します。

-- construct an instance of class class_name for type for_type
-- funcs is a list of instance method names with a corresponding
-- function to build the method body
gen_instance :: Name -> TypeQ -> [Constructor] -> Funcs -> DecQ
gen_instance class_name for_type constructors funcs = 
  instanceD (cxt [])
    (appT (conT class_name) for_type)
    (map func_def funcs) 
      where func_def (func_name, gen_func) 
                = funD func_name -- method name
                  -- generate function body for each constructor
                  (map (gen_clause gen_func) constructors)

上記のヘルパー関数。

-- Generate the pattern match and function body for a given method and
-- a given constructor. func_body is a function that generations the
-- function body
gen_clause :: (Constructor -> [ExpQ] -> ExpQ) -> Constructor -> ClauseQ
gen_clause func_body data_con@(con_name, components) = 
      -- create a parameter for each component of the constructor
   do vars <- mapM var components
      -- function (unnamed) that pattern matches the constructor 
      -- mapping each component to a value.
      (clause [(conP con_name (map varP vars))]
            (normalB (func_body data_con (map varE vars))) [])
       -- create a unique name for each component. 
       where var (_, typ) 
                 = newName 
                   $ case typ of 
                     (ConT name) -> toL $ nameBase name
                     otherwise   -> "parm"
               where toL (x:y) = (toLower x):y

unCapalize :: [Char] -> [Char]
unCapalize (x:y) = (toLower x):y

SYB III / Replib 0.2から取得したいくつかの借りたヘルパーコード。

typeInfo :: DecQ -> Q (Name, [Name], [(Name, Int)], [(Name, [(Maybe Name, Type)])])
typeInfo m =
     do d <- m
        case d of
           d@(DataD _ _ _ _ _) ->
            return $ (simpleName $ name d, paramsA d, consA d, termsA d)
           d@(NewtypeD _ _ _ _ _) ->
            return $ (simpleName $ name d, paramsA d, consA d, termsA d)
           _ -> error ("derive: not a data type declaration: " ++ show d)

     where
        consA (DataD _ _ _ cs _)    = map conA cs
        consA (NewtypeD _ _ _ c _)  = [ conA c ]

        {- This part no longer works on 7.6.3
        paramsA (DataD _ _ ps _ _) = ps
        paramsA (NewtypeD _ _ ps _ _) = ps
        -}

        -- Use this on more recent GHC rather than the above
        paramsA (DataD _ _ ps _ _) = map nameFromTyVar ps
        paramsA (NewtypeD _ _ ps _ _) = map nameFromTyVar ps

        nameFromTyVar (PlainTV a) = a
        nameFromTyVar (KindedTV a _) = a


        termsA (DataD _ _ _ cs _) = map termA cs
        termsA (NewtypeD _ _ _ c _) = [ termA c ]

        termA (NormalC c xs)        = (c, map (\x -> (Nothing, snd x)) xs)
        termA (RecC c xs)           = (c, map (\(n, _, t) -> (Just $ simpleName n, t)) xs)
        termA (InfixC t1 c t2)      = (c, [(Nothing, snd t1), (Nothing, snd t2)])

        conA (NormalC c xs)         = (simpleName c, length xs)
        conA (RecC c xs)            = (simpleName c, length xs)
        conA (InfixC _ c _)         = (simpleName c, 2)

        name (DataD _ n _ _ _)      = n
        name (NewtypeD _ n _ _ _)   = n
        name d                      = error $ show d

simpleName :: Name -> Name
simpleName nm =
   let s = nameBase nm
   in case dropWhile (/=':') s of
        []          -> mkName s
        _:[]        -> mkName s
        _:t         -> mkName t
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top