Haskell 多态函数中的GADT
我有一个函数的问题,我想使非常多态。 我想对函数进行积分,无论是解析积分还是数值积分。当进行分析积分时,我提供结果。 在数字的情况下,我想使用各种方法,现在,来自的tanhshinh例程。 我还想了解更多关于GADT的知识,所以我试图找到一个使用GADT的解决方案 到目前为止,我有以下几点:Haskell 多态函数中的GADT,haskell,gadt,Haskell,Gadt,我有一个函数的问题,我想使非常多态。 我想对函数进行积分,无论是解析积分还是数值积分。当进行分析积分时,我提供结果。 在数字的情况下,我想使用各种方法,现在,来自的tanhshinh例程。 我还想了解更多关于GADT的知识,所以我试图找到一个使用GADT的解决方案 到目前为止,我有以下几点: import qualified Data.VectorSpace as DV import Numeric.Integration.TanhSinh data IntegrationType a b
import qualified Data.VectorSpace as DV
import Numeric.Integration.TanhSinh
data IntegrationType a b where
MkAnalytic :: (DV.AdditiveGroup b) => (c -> b) -> c -> c -> IntegrationType Analytic b
MkNumeric :: NumericType -> IntegrationType Numeric [Result]
data Analytic = Analytic
data Numeric = Numeric
data Method = Trapez | Simpson
data IntBounds = Closed | NegInfPosInf | ZeroInf
data NumericType = MkSingleCoreTanhSinh IntBounds Method (Double -> Double) Double Double
| MkParallelTanhSinhExplicit IntBounds (Strategy [Double]) Method (Double -> Double) Double Double
| MkParallelTanhSinh IntBounds Method (Double -> Double) Double Double
integrate :: IntegrationType a b -> b
integrate (MkAnalytic f l h) = f h DV.^-^ f l
integrate (MkNumeric (MkSingleCoreTanhSinh Closed Trapez f l h )) = trap f l h
integrate (MkNumeric (MkSingleCoreTanhSinh Closed Simpson f l h )) = simpson f l h
这段代码可以编译,因为我在构造函数MkNumeric中明确声明类型变量b是
[Result]
我为什么要这么做?我可以不将类型变量b保留为中的吗
data IntegrationType a b where
MkNumeric :: NumericType -> IntegrationType Numeric b
当我这样做时,我会得到一个错误:
类型
integrate :: IntegrationType a b -> b
表示,对于我选择的任何a
和b
,如果我调用integration
,使用类型为IntegrationType a b
的值,我将返回类型为b
的值。当你定义
MkNumeric :: NumericType -> IntegrationType Numeric b
您可以让应用构造函数的人决定b
是什么。所以我可以使用MkNumeric
来制造一个值,比如说,类型IntegrationType Numeric Int
。但是您的integrate
知道如何生成[结果]
,而不是Int
在工作代码中,只要
integrate
通过匹配MkNumeric
“打开证据箱”,它就会知道b~[Result]
,因此它可以返回该类型的内容。好的,我可以理解这一点。但是,如果我不仅要返回一个[Result]
,而且可能还要返回一对类似([Result],[Result])
的结果,该怎么办呢。基本上,我希望能够使用我的integrate
函数返回一组类型。这就是我所认为的,只要说MkNumeric::numericype->IntegrationType Numeric b
@TheMADMAN,最大的问题是一旦你有了结果,你可以对它们做什么。在完全依赖类型的语言中,可以使结果类型以任意方式依赖于输入值,但使用结果需要证明它具有所需的类型(这种机制似乎主要适用于元编程的性质)。在哈斯克尔,我们不能这样做;结果类型不能依赖于输入值。
MkNumeric :: NumericType -> IntegrationType Numeric b