从ADT恢复GADT时输入问题

时间:2012-05-25 00:08:11

标签: haskell

我想将我的键入的GADT(GExpr)放入一个hashmap,所以我首先将它转换为相应的单态ADT(Expr)。当我从hashmap中查找时,我无法将单态ADT转换回GADT。

以下是简化版。基本上有两个功能,“昏暗”和“gexprOfExpr”,我只能让其中一个同时工作。我想做什么不可能?

{-# OPTIONS_GHC -Wall #-}
{-# Language GADTs #-}

type ListDim = [Int]

data DIM0 = DIM0
data DIM1 = DIM1

class Shape sh where
  shapeOfList :: ListDim -> sh

instance Shape DIM0 where
  shapeOfList _ = DIM0
instance Shape DIM1 where
  shapeOfList _ = DIM1

data Expr = EConst ListDim Double
          | ESum ListDim Int

data GExpr sh where
  GRef :: sh -> Int -> GExpr sh
  GConst :: sh -> Double -> GExpr sh
  GSum :: GExpr DIM1 -> GExpr DIM0  -- GADT, this works for "dim"
--  GSum :: GExpr DIM1 -> GExpr sh -- phantom type, this works for "gexprOfExpr"

dim :: GExpr sh -> sh
dim (GRef sh _) = sh
dim (GConst sh _) = sh
dim (GSum _) = DIM0

gexprOfExpr :: Shape sh => Expr -> GExpr sh
gexprOfExpr (EConst lsh x) = GConst (shapeOfList lsh) x
gexprOfExpr (ESum lsh k) = GSum $ GRef (shapeOfList lsh) k

注意:我确实知道我正在尝试恢复的类型。如果它会有所帮助,那就没关系了:

gexprOfExpr :: Shape sh => sh -> Expr -> GExpr sh

1 个答案:

答案 0 :(得分:3)

来自#haskell的Saizan给了我一个提示答案。这是工作版本:

{-# OPTIONS_GHC -Wall #-}
{-# Language GADTs #-}

import Data.Maybe

type ListDim = [Int]

data DIM0 = DIM0
data DIM1 = DIM1

class Shape sh where
  shapeOfList :: ListDim -> sh
  maybeGExprOfExpr :: Expr -> Maybe (GExpr sh)
  maybeGExprOfExpr _ = Nothing

instance Shape DIM0 where
  shapeOfList _ = DIM0
  maybeGExprOfExpr (ESum lsh k) = Just $ GSum $ GRef (shapeOfList lsh) k
  maybeGExprOfExpr _ = Nothing

instance Shape DIM1 where
  shapeOfList _ = DIM1


data Expr = EConst ListDim Double
          | ESum ListDim Int

data GExpr sh where
  GRef :: sh -> Int -> GExpr sh
  GConst :: sh -> Double -> GExpr sh
  GSum :: GExpr DIM1 -> GExpr DIM0

dim :: GExpr sh -> sh
dim (GRef sh _) = sh
dim (GConst sh _) = sh
dim (GSum _) = DIM0

gexprOfExpr :: Shape sh => Expr -> GExpr sh
gexprOfExpr (EConst lsh x) = GConst (shapeOfList lsh) x
gexprOfExpr e@(ESum _ _) = fromJust $ maybeGExprOfExpr e