24

什么是约束种类

为什么有人会使用它(在实践中)?

到底有什么好处呢?

能否举一个简单的代码示例来说明前两个问题的答案?

例如,为什么在代码中使用它?

4

1 回答 1

31

好吧,我会提到它允许你做的两件实际的事情:

  1. 通过类型类约束参数化类型
  2. 编写允许其实例指定所需约束的类型类。

也许最好用一个例子来说明这一点。一个经典的 Haskell 缺点是,你不能Functor为对它们的类​​型参数施加类约束的类型创建实例。例如,库Set中的类containers,它需要Ord对其元素进行约束。原因是在“香草”Haskell 中,您必须对类本身进行约束:

class OrdFunctor f where
    fmap :: Ord b => (a -> b) -> f a -> f b

...但是此类仅适用于需要特别Ord约束的类型。不是通用解决方案!

那么,如果我们可以采用该类定义并抽象出Ord约束,让各个实例说出它们需要什么约束呢?好吧,ConstraintKinds再加上TypeFamilies允许:

{-# LANGUAGE ConstraintKinds, TypeFamilies, FlexibleInstances #-}

import Prelude hiding (Functor(..))
import GHC.Exts (Constraint)
import Data.Set (Set)
import qualified Data.Set as Set

-- | A 'Functor' over types that satisfy some constraint.
class Functor f where
   -- | The constraint on the allowed element types.  Each
   -- instance gets to choose for itself what this is.
   type Allowed f :: * -> Constraint

   fmap :: Allowed f b => (a -> b) -> f a -> f b

instance Functor Set where
    -- | 'Set' gets to pick 'Ord' as the constraint.
    type Allowed Set = Ord
    fmap = Set.map

instance Functor [] where
    -- | And `[]` can pick a different constraint than `Set` does.
    type Allowed [] = NoConstraint
    fmap = map

-- | A dummy class that means "no constraint."
class NoConstraint a where

-- | All types are trivially instances of 'NoConstraint'.
instance NoConstraint a where

(请注意,这不是创建Functor实例的唯一障碍Set;请参阅此讨论。此外,感谢这个答案的NoConstraint技巧。)

不过,这种解决方案还没有被普遍采用,因为ConstraintKinds它或多或少还是一个新特性。


另一个用途ConstraintKinds是通过类约束或类对类型进行参数化。我将重现我编写的这个 Haskell“形状示例”代码

{-# LANGUAGE GADTs, ConstraintKinds, KindSignatures, DeriveDataTypeable #-}
{-# LANGUAGE TypeOperators, ScopedTypeVariables, FlexibleInstances #-}

module Shape where

import Control.Applicative ((<$>), (<|>))
import Data.Maybe (mapMaybe)
import Data.Typeable
import GHC.Exts (Constraint)

-- | Generic, reflective, heterogeneous container for instances
-- of a type class.
data Object (constraint :: * -> Constraint) where
    Obj :: (Typeable a, constraint a) => a -> Object constraint
           deriving Typeable

-- | Downcast an 'Object' to any type that satisfies the relevant
-- constraints.
downcast :: forall a constraint. (Typeable a, constraint a) =>
            Object constraint -> Maybe a
downcast (Obj (value :: b)) = 
  case eqT :: Maybe (a :~: b) of
    Just Refl -> Just value
    Nothing -> Nothing

这里类型的参数Object是一个类型类(kind * -> Constraint),所以你可以有像Object Shapewhere Shapeis a class 这样的类型:

class Shape shape where
  getArea :: shape -> Double

-- Note how the 'Object' type is parametrized by 'Shape', a class 
-- constraint.  That's the sort of thing ConstraintKinds enables.
instance Shape (Object Shape) where
    getArea (Obj o) = getArea o

Object类型的作用是两个特征的组合:

  1. 存在类型(此处由 启用GADTs),它允许我们将异构类型的值存储在同一Object类型中。
  2. ConstraintKinds,它允许我们而不是硬编码Object到某些特定的类约束集,而是让该Object类型的用户指定他们想要的约束作为该Object类型的参数。

现在有了它,我们不仅可以制作一个异构的Shape实例列表:

data Circle = Circle { radius :: Double }
            deriving Typeable

instance Shape Circle where
  getArea (Circle radius) = pi * radius^2


data Rectangle = Rectangle { height :: Double, width :: Double }
               deriving Typeable

instance Shape Rectangle where
  getArea (Rectangle height width) = height * width

exampleData :: [Object Shape]
exampleData = [Obj (Circle 1.5), Obj (Rectangle 2 3)]

...但是由于我们可以向下转换Typeable的约束:如果我们正确猜测包含在 an 中的类型,我们可以恢复该原始类型:ObjectObject

-- | For each 'Shape' in the list, try to cast it to a Circle.  If we
-- succeed, then pass the result to a monomorphic function that 
-- demands a 'Circle'.  Evaluates to:
--
-- >>> example
-- ["A Circle of radius 1.5","A Shape with area 6.0"]
example :: [String]
example = mapMaybe step exampleData
  where step shape = describeCircle <$> (downcast shape)
                 <|> Just (describeShape shape)

describeCircle :: Circle -> String
describeCircle (Circle radius) = "A Circle of radius " ++ show radius

describeShape :: Shape a => a -> String
describeShape shape = "A Shape with area " ++ show (getArea shape)
于 2015-07-09T21:27:33.413 回答