¿Cómo trabajar con AST con anotación Cofree?
Tengo este simpleExpr
AST y puedo convertirlo fácilmente aString
.
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]
Ahora quiero agregarle datos adicionales. Entonces estoy tratando de usarCofree
type LineNumber = Int
type Expr2 = Cofree ExprF LineNumber
Puedo convertirExpr
aExpr2
addLineNumbers :: Expr -> Expr2
addLineNumbers = cata $ \case
e@(Const _) -> 1 :< e
e -> 2 :< e
Pero no puedo entender cómo convertirExpr2
aString
convertToString2 :: Expr2 -> String
convertToString2 = cata $ \case
e@(_ :< (Const x)) -> show x
e@(_ :< (Add x y)) -> unwords [x, "+", y]
Además, ¿es Cofree la mejor manera de resolver este problema de anotación?