AST をポリモーフィックに表現しない理由
data Term term = Var String
| Num Integer
| Expr [term]
あなたの元のTerm
タイプは
newtype SimplTerm = SimplTerm (Term (SimplTerm))
ビューパターンを使用して、必要なことを簡単に行うことができます
data AtLine = AtLine (Term AtLine) Integer
view :: AtLine -> Term AtLine
view (AtLine x _) = x
eval (view -> Var name) = lookup name
eval (view -> Num n) = numResult n
eval (view -> Expr expr) = listResult (map eval expr)
またはビューをポリモーフィックにする
class AST t where
term :: t -> Term t
instance AST SimplTemr where
term (SimplTemr x) = x
instance AST AtLine where
term (AtLine x _) = x
eval :: AST t => t -> Result
eval (view -> Var name) = lookup name
eval (view -> Num n) = numResult n
eval (view -> Expr expr) = listResult (map eval expr)
エラー処理のために、ビューパターンをモナドに表示する方法があればいいのにと思いますが、それは人生です(view
関数がcpsで実行され、値を返すのではなく継続を引数として取る場合に可能です)。