gpt4 book ai didi

haskell - 从 ADT 恢复 FAST 时的类型问题

转载 作者:行者123 更新时间:2023-12-01 02:34:42 24 4
gpt4 key购买 nike

我想将我输入的 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

最佳答案

来自#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

关于haskell - 从 ADT 恢复 FAST 时的类型问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10746926/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com