Haskell Typeclass简写

所以,我有一对类型类,我会一起使用,我想避免每次都指定。基本上,而不是放

:: (Ord a, Fractional a, Ord b, Fractional b, ... Ord z, Fractional z) =>

在所有类型规格的开始,我宁愿放

:: (OrdFractional a, OrdFractional b, ... OrdFractional z)

所以,我最初的想法是如何做到这一点只是声明一个新的类型类

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)

但是,这并不像我所希望的那样自动运行:

% 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)

手动创建实例似乎是一个拖动,接下来,我想我可能会尝试自动创建实例:

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)

但编译器不喜欢这样:

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'

那么有办法可以做到吗?

随着GHC 7.4中引入的ConstraintKinds扩展,约束现在是种类的约束,所以你可以使用普通类型的同义词来获得你想要的东西:

{-# LANGUAGE ConstraintKinds #-}

type OrdFractional a = (Ord a, Fractional a)
http://stackoverflow.com/questions/306284/haskell-typeclass-shorthand

本站文章除注明转载外,均为本站原创或编译
转载请明显位置注明出处:Haskell Typeclass简写