Ich habe diese einfache Expr
AST und ich kann es leicht zu String
konvertieren.Wie mit AST mit Cofree Annotation arbeiten?
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
[email protected](Const x) -> show x
[email protected](Add x y) -> unwords [x, "+", y]
Jetzt möchte ich eine zusätzliche Daten hinzufügen. So versuche ich Cofree
type LineNumber = Int
type Expr2 = Cofree ExprF LineNumber
I Expr
-Expr2
addLineNumbers :: Expr -> Expr2
addLineNumbers = cata $ \case
[email protected](Const _) -> 1 :< e
e -> 2 :< e
Aber ich kann nicht herausfinden, umwandeln kann zu verwenden, wie Expr2
-String
convertToString2 :: Expr2 -> String
convertToString2 = cata $ \case
[email protected](_ :< (Const x)) -> show x
[email protected](_ :< (Add x y)) -> unwords [x, "+", y]
auch zu konvertieren, ist Cofree der beste Weg, um dieses Annotationsproblem zu lösen?
Interessante Frage. Ich habe momentan keine Antwort für dich, aber ich werde diesen Gedanken teilen. 'Free' ist induktiv und' Cofree' ist koinduktiv. Das heißt, es ist garantiert produktiv, wenn man eine (gut erzogene) freie Monade mit einer (totalen) Algebra für einen beliebigen Funktor abknickt und die Bildung einer Cofree-Komonade mit Hilfe einer Kohlebrade garantiert. Andersherum ist das nicht wahr –