ram*_*ion 22 haskell typeclass
所以,我有一对我将一起使用的类型类,我想避免每次都指定.基本上,而不是放
:: (Ord a, Fractional a, Ord b, Fractional b, ... Ord z, Fractional z) =>
Run Code Online (Sandbox Code Playgroud)
在我所有类型规范的开头,我宁愿放
:: (OrdFractional a, OrdFractional b, ... OrdFractional z)
Run Code Online (Sandbox Code Playgroud)
所以,我最初的想法是如何声明一个新的类型类
module Example where
class (Fractional a, Ord a) => OrdFractional a
example :: (OrdFractional a, OrdFractional b) => (a,b) -> (a,b) -> (a,b) -> Bool
example (x1,y1) (x2,y2) (x3,y3) = (x1/x2 < x2/x3) && (y1/y2 < y2/y3)
Run Code Online (Sandbox Code Playgroud)
但这并不像我希望的那样自动运行:
% ghci
Prelude> :l Example.hs
Ok, modules loaded: Example.
Prelude Example> example (1::Float,3::Float) (2,2) (3,1)
<interactive>:1:0:
No instance for (OrdFractional Float)
arising from a use of `example' at <interactive>:1:0-39
Possible fix:
add an instance declaration for (OrdFractional Float)
In the expression: example (1 :: Float, 3 :: Float) (2, 2) (3, 1)
In the definition of `it':
it = example (1 :: Float, 3 :: Float) (2, 2) (3, 1)
Run Code Online (Sandbox Code Playgroud)
手动创建实例似乎是一种拖累,接下来,我想我可能会尝试自动创建实例:
module Example where
class OrdFractional a
instance (Fractional a, Ord a) => OrdFractional a
example :: (OrdFractional a, OrdFractional b) => (a,b) -> (a,b) -> (a,b) -> Bool
example (x1,y1) (x2,y2) (x3,y3) = (x1/x2 < x2/x3) && (y1/y2 < y2/y3)
Run Code Online (Sandbox Code Playgroud)
但编译器并不喜欢这样:
ghc -c Example.hs
Example.hs:4:0:
Illegal instance declaration for `OrdFractional a'
(All instance types must be of the form (T a1 ... an)
where a1 ... an are type *variables*,
and each type variable appears at most once in the instance head.
Use -XFlexibleInstances if you want to disable this.)
In the instance declaration for `OrdFractional a'
Run Code Online (Sandbox Code Playgroud)
那么我有办法做到这一点吗?
jav*_*ard 32
使用GHC 7.4中引入的ConstraintKinds扩展,约束现在是类型的类型Constraint,因此您可以使用普通类型同义词来获得您想要的内容:
{-# LANGUAGE ConstraintKinds #-}
type OrdFractional a = (Ord a, Fractional a)
Run Code Online (Sandbox Code Playgroud)
eph*_*ent 10
当编译器说" Use -XFlexibleInstances"时,你应该尝试添加
{-# LANGUAGE FlexibleInstances #-}
Run Code Online (Sandbox Code Playgroud)
到你的源头(并阅读文档,了解它的作用,当然!).
在这种特定情况下,这将使您的代码工作:
{-# LANGUAGE FlexibleInstances, UndecidableInstances #-}
Run Code Online (Sandbox Code Playgroud)
为了=>在实例头上启用上下文,需要灵活的实例,并且需要不可判定的实例,因为编译器在处理OrdFractional a上下文时可以结束添加Fractional a和Ord a上下文 - 这不会直接帮助最终确定a,并且适当的可怕情况,类型检查可能会分歧; 编译器真的不喜欢这样.(如果编译器永远存在或者内存不足,你可能不会喜欢它.)