4

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

以下是简化版。基本上有两个函数,“dim”和“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
4

1 回答 1

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
于 2012-05-25T00:42:55.310 回答