2013-04-14 74 views
4

想要找到遗留代码库中的所有位置,以便在if条件下使用变量foo。如何添加类型实例声明

---- Why Haskell Is Worth Learning

我的代码是

import Language.C 
import Data.Generics 
import Control.Monad 
import Text.Read 

parseAndFindFoos :: FilePath -> IO (Either ParseError [Position]) 
parseAndFindFoos path = liftM (fmap findFooLocations) (parseCFilePre path) 
findFooLocations input = fmap posOf (listify isIfOfInterest input) 
isIfOfInterest (CIf cond _ _ _) = not (null (listify isFooIdent cond)) 
isFooIdent (Ident name) = (name == "foo") 

我怎么能添加对(分型词位)的实例声明?

回答

8
{-# LANGUAGE DeriveDataTypeable, StandaloneDeriving #-} 
import Data.Typeable 

deriving instance Typeable Lexeme 

应该工作。

然而,有一个缺陷,这只有当这个实例要在库中定义时才真正适用。 Lexeme将作为Typeable的实例,并且如果任何其他库包含类似实例,则会有冲突。不幸的是,你真的可以确保你不添加Lexeme的全局Typeable实例,或者希望它在某个时刻被添加到base,或者使用newtype包装并手动包装和解包Lexeme

newtype LexemeWrapper = WrapLexeme { unwrapLexeme :: Lexeme } deriving Typeable