Movatterモバイル変換


[0]ホーム

URL:


base-4.12.0.0: Basic libraries

Copyright(c) The University of Glasgow 2001
LicenseBSD-style (see the file libraries/base/LICENSE)
Maintainerlibraries@haskell.org
Stabilityprovisional
Portabilityportable
Safe HaskellUnsafe
LanguageHaskell2010

Data.Coerce

Contents

Description

Safe coercions between data types.

More in-depth information can be found on theRoles wiki page

Since: 4.7.0.0

Synopsis

Safe coercions

coerce ::Coercible a b => a -> b#

The functioncoerce allows you to safely convert between values of types that have the same representation with no run-time overhead. In the simplest case you can use it instead of a newtype constructor, to go from the newtype's concrete type to the abstract type. But it also works in more complicated settings, e.g. converting a list of newtypes to a list of concrete types.

class a ~R# b =>Coercible (a :: k0) (b :: k0)#

Coercible is a two-parameter class that has instances for typesa andb if the compiler can infer that they have the same representation. This class does not have regular instances; instead they are created on-the-fly during type-checking. Trying to manually declare an instance ofCoercible is an error.

Nevertheless one can pretend that the following three kinds of instances exist. First, as a trivial base-case:

instance Coercible a a

Furthermore, for every type constructor there is an instance that allows to coerce under the type constructor. For example, letD be a prototypical type constructor (data ornewtype) with three type arguments, which have rolesnominal,representational resp.phantom. Then there is an instance of the form

instance Coercible b b' => Coercible (D a b c) (D a b' c')

Note that thenominal type arguments are equal, therepresentational type arguments can differ, but need to have aCoercible instance themself, and thephantom type arguments can be changed arbitrarily.

The third kind of instance exists for everynewtype NT = MkNT T and comes in two variants, namely

instance Coercible a T => Coercible a NT
instance Coercible T b => Coercible NT b

This instance is only usable if the constructorMkNT is in scope.

If, as a library author of a type constructor likeSet a, you want to prevent a user of your module to writecoerce :: Set T -> Set NT, you need to set the role ofSet's type parameter tonominal, by writing

type role Set nominal

For more details about this feature, please refer toSafe Coercions by Joachim Breitner, Richard A. Eisenberg, Simon Peyton Jones and Stephanie Weirich.

Since: ghc-prim-4.7.0.0

Produced byHaddock version 2.20.0


[8]ページ先頭

©2009-2025 Movatter.jp