[英]Converting Data.Reify explicit sharing graph to AST with de Bruijn indices
[英]how to reify a list of data using Data.Reify?
我試着閱讀這篇論文( http://www.ittc.ku.edu/csdl/fpg/sites/default/files/Gill-09-TypeSafeReification.pdf )並設法重新啟用我的符號表達式類型,但我可以'弄清楚如何重新列出它們的清單。 這是簡化的代碼:
{-# OPTIONS_GHC -Wall #-}
{-# Language TypeOperators #-}
{-# Language TypeFamilies #-}
{-# Language FlexibleInstances #-}
import Control.Applicative
import Data.Reify
-- symbolic expression type
data Expr a = EConst a
| EBin (Expr a) (Expr a)
deriving Show
-- corresponding node type
data GraphExpr a b = GConst a
| GBin b b
deriving Show
instance MuRef (Expr a) where
type DeRef (Expr a) = GraphExpr a
mapDeRef _ (EConst c) = pure (GConst c)
mapDeRef f (EBin u v) = GBin <$> f u <*> f v
-- this works as expected
main :: IO ()
main = reifyGraph (EBin x (EBin x y)) >>= print
where
x = EConst "x"
y = EConst "y"
-- (output: "let [(1,GBin 2 3),(3,GBin 2 4),(4,GConst "y"),(2,GConst "x")] in 1")
-- but what if I want to reify a list of Exprs?
data ExprList a = ExprList [Expr a]
data GraphList a b = GraphList [GraphExpr a b]
instance MuRef (ExprList a) where
type DeRef (ExprList a) = GraphList a
-- mapDeRef f (ExprList xs) = ???????
我有完全相同的問題,我找到了一個使用data-reify的解決方案。
為了得到解決方案,你必須意識到的事情是:1。即使EDSL沒有列表,圖表類型也可以包含它們2.可以將不同類型的數據統一到相同的結果類型。
所以我們首先在結果類型中添加列表構造函數:
data GraphExpr a b = GConst a
| GBin b b
| Cons b b
| Nil
deriving Show
然后我們需要MuRef的第二個實例,它將Expr a的列表統一到GraphExpr。
instance MuRef [Expr a] where
type DeRef [Expr a] = GraphExpr a
mapDeRef _ [] = pure Nil
mapDeRef f (x:xs) = Cons <$> f x <*> f xs
現在有了這個,如果我們嘗試重新列出一個列表表達式
reified = reifyGraph [EBin x (EBin x y), Ebin y (EBin x y)]
where x = EConst "x"
y = EConst "y"
我們會得到結果
let [(1,Cons 2 6),(6,Cons 7 9),(9,Nil),(7,GBin 5 8),(8,GBin 3 5),(2,GBin 3 4),(4,GBin 3 5),(5,GConst "y"),(3,GConst "x")] in 1
要從此圖中提取已知的節點ID列表,我們可以定義一個小函數來遍歷Conses並將節點ID從它們提取到列表中。
walkConses :: Graph (GraphExpr t) -> [Unique]
walkConses (Graph xs root) = go (lookup root xs)
where
go (Just (Cons n1 n2)) = n1 : go (lookup n2 xs)
go (Just Nil) = []
(如果圖形很大,那么在開始漫步之前將它們轉換為IntMap可能是個好主意)
這看起來像是一個部分函數,但是因為我們知道DAG的根將始終是Cons節點(因為我們重新列出了一個列表),並且因為我們知道所有node-id都在xs中,所以這個函數將返回一個列表結果列表中的所有node-id。
因此,如果我們在結果圖上運行walkConses,我們將得到結果:
[2, 7]
希望這會有所幫助,我也一直在努力解決這個問題。
你真的不能用MuRef做到這一點。 GraphLists不包含GraphLists。 您可以依次重新啟動每個Expr並編寫一個一次性組合器,將它們粉碎到您的GraphList中:
只需在ExprList內容上使用遍歷reifyGraph。
此外,后者都應該是新類型。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.