{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE FunctionalDependencies #-}
class Fractional f => Point3D p f | p -> f where
x :: p -> f
y :: p -> f
z :: p -> f
class (Fractional fr, Point3D p fr, Foldable f) => HasPoints3D ps p f where
points :: ps -> f p
我创建了 Point3D
类来涵盖 3D 点的不同实现。我创建了 HasPoints3D
类来涵盖所有具有某些点的事物。 Point3D
定义中的第二个类型变量f
由第一个类型变量p
决定。所以,我认为 HasPoints3D
的定义没有问题,因为 fr
可以由 p
决定。
我知道这可能会导致 typechecker loop .所以,我添加了 {-# LANGUAGE UndecidableInstances #-}
。但它不起作用,它说 Not in scope: type variable ‘fr’
。是否有另一个 haskell 扩展来完成这项工作?或者 haskell 无法处理这种情况?
最佳答案
就我个人而言,我倾向于避免函数依赖,而是尽可能使用类型族。我认为它通常更简单,并且可以避免此类问题。
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE TypeFamilies #-}
class Fractional (F p) => Point3D p where
type F p
x :: p -> F p
y :: p -> F p
z :: p -> F p
class (Fractional (F p), Point3D p, Foldable f) => HasPoints3D ps p f where
points :: ps -> f p
关于haskell - 如何使用具有功能依赖性的类来定义另一个类的约束?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72128820/