【发布时间】:2019-09-23 11:55:32
【问题描述】:
我想写一个这样的类:
class C c where
op :: c -> c -> Bool
class A b => B b where
func :: C c => b -> c -- ^ type 'c' is random(forall).
func2 :: b -> b -> Bool
func2 x y = func b `op` func c
这里,c 是一个受C 限制的类型,这个限制将在 func2 中使用。
但这不能是编译器。 c 类型不是真正的类型。我尝试添加forall 或使用TypeFamilies,但他们都无法做到这一点。 TypeFamilies 看起来不错,但它不能在函数定义中使用 with 限制,例如 C c => b -> c 或 `type X x :: C * => *。
我必须使用(A b, C c) => B b c 来定义这个类吗?我有另一个类与 B 一起使用,例如 B b => D d b。如果为 B 类添加一个参数,则 D 类还需要一个参数。其实Seq a会和D类一起使用,不能匹配D d b。
编辑:再描述一个。
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE FlexibleInstances #-}
module Main where
type Ta = (Integer, Integer)
newtype Tb t = Tb { tb :: [t] } deriving Show
class Eq a => A a where
a1f :: Ord b => a -> b
a2f :: a -> a -> Bool
a2f x y = a1f x >= a1f y
instance A Ta where
a1f (_, y) = y
class A a => B b a where
op :: b a -> b a
instance B Tb Ta where
op x = x
main :: IO ()
main = putStrLn $ show $ op $ (Tb [(1, 1)] :: Tb Ta)
编译器会抱怨a2f :: b -> Bool:
• Could not deduce (Ord a0) arising from a use of ‘>=’
from the context: A a
bound by the class declaration for ‘A’ at test.hs:10:15
The type variable ‘a0’ is ambiguous
These potential instances exist:
instance Ord Ordering -- Defined in ‘GHC.Classes’
instance Ord Integer
-- Defined in ‘integer-gmp-1.0.2.0:GHC.Integer.Type’
instance Ord a => Ord (Maybe a) -- Defined in ‘GHC.Maybe’
...plus 22 others
...plus four instances involving out-of-scope types
(use -fprint-potential-instances to see them all)
• In the expression: a1f x >= a1f y
In an equation for ‘a2f’: a2f x y = a1f x >= a1f y
EDIT2:使用类型族
...
class Eq a => A a where
type AT a :: *
a1f :: Ord (AT a) => a -> AT a
a2f :: a -> a -> Bool
a2f x y = a1f x >= a2f y
instance A Ta where
type AT Ta = Integer
a1f (_, y) = y
...
它会显示错误:
• Could not deduce (Ord (AT a)) arising from a use of ‘>=’
from the context: A a
bound by the class declaration for ‘A’ at test.hs:10:15
• In the expression: a1f x >= a1f y
In an equation for ‘a2f’: a2f x y = a1f x >= a1f y
【问题讨论】:
-
forall并不意味着随机。这意味着the caller chooses。在这种情况下,调用者是func2,你必须告诉它如何选择。你能多说一点你想要完成的事情,以便我们可以就如何解决这个问题提供更好的建议吗?有几种(矛盾的)前进方式,目前尚不清楚哪种方式最适合您。 -
@DanielWagner 我的整个程序有很多行,这只是我其他课程的练习。我在问题中添加了一个示例,这是我所拥有的最小化问题。你想给我一些建议吗?
-
你不需要向我们展示你的整个程序来解释你想要完成什么,但你确实需要谈论你想要实现的计算,以及你为什么相信这会引导你不可避免地需要具有这种形状的类型类来实现该计算。