Wie kann ich mit AST mit Cofree Annotation arbeiten?
Ich habe diese einfacheExpr
AST und ich können es leicht zu @ konvertierString
.
import Prelude hiding (Foldable)
import qualified Prelude
import Data.Foldable as F
import Data.Functor.Foldable
import Data.Monoid
import Control.Comonad.Cofree
data ExprF r = Const Int
| Add r r
deriving ( Show, Eq, Ord, Functor, Prelude.Foldable )
type Expr = Fix ExprF
testExpr = Fix $ Add (Fix (Const 1)) (Fix (Const 2))
convertToString :: Expr -> String
convertToString = cata $ \case
e@(Const x) -> show x
e@(Add x y) -> unwords [x, "+", y]
Jetzt möchte ich zusätzliche Daten hinzufügen. Also versuche ich @ zu benutzCofree
type LineNumber = Int
type Expr2 = Cofree ExprF LineNumber
Ich kann @ konvertierExpr
zuExpr2
addLineNumbers :: Expr -> Expr2
addLineNumbers = cata $ \case
e@(Const _) -> 1 :< e
e -> 2 :< e
Aber ich kann nicht herausfinden, wie man @ konvertieExpr2
zuString
convertToString2 :: Expr2 -> String
convertToString2 = cata $ \case
e@(_ :< (Const x)) -> show x
e@(_ :< (Add x y)) -> unwords [x, "+", y]
Auch, ist Cofree der beste Weg, um dieses Annotationsproblem zu lösen?