{-# 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 Point 的各種實作。我HasPoints3D上課是為了涵蓋所有有觀點的東西。f定義中的第二個型別變數Point3D由第一個型別變數決定p。所以,我認為這個定義HasPoints3D沒有問題,因為fr可以由p.
我知道這可能會導致typechecker loop。所以,我添加了{-# LANGUAGE UndecidableInstances #-}. 但它不起作用,它說Not in scope: type variable ‘fr’。是否有另一個 haskell 擴展來完成這項作業?還是haskell無法處理這種情況?
uj5u.com熱心網友回復:
就個人而言,我傾向于避免函式依賴,而是盡可能使用型別族。我認為它通常更簡單,并且避免了這樣的問題。
{-# 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
uj5u.com熱心網友回復:
我同意 chiPoints3D一開始可能不應該是一個多引數類。但是,如果您對此無能為力,您仍然可以在 中使用關聯的型別族HasPoints3D:
{-# LANGUAGE ..., TypeFamilies, FlexibleContexts #-}
import Data.Kind (Type)
class ( Fractional (DirectionalComponent ps p f)
, Point3D p (DirectionalComponent ps p f)
, Foldable f ) => HasPoints3D ps p f where
type DirectionalComponent ps p f :: Type
points :: ps -> f p
順便說一句,我發現Point3D抽象非常可疑。為什么你需要一個型別類呢?這聽起來像是一種具體型別
data V3 s = V3 {x,y,z :: !s}
不要求具有任何特定坐標軸的特定三個維度可能更有意義,而是在您正在作業的向量空間上抽象。
同樣,你為什么需要這個HasPoints3D類?為什么不f p按原樣使用,f并p根據需要單獨使用適當的約束?
建議閱讀:何時使用型別類的經驗法則。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/474033.html
標籤:哈斯克尔
