Difference between revisions of "Multi-parameter type class"

From HaskellWiki
Jump to navigation Jump to search
m (→‎About: minor wibble)
(fix ghc dev wiki link)
(7 intermediate revisions by 4 users not shown)
Line 1: Line 1:
 
[[Category:Language extensions]]
 
[[Category:Language extensions]]
  +
[[Category:Glossary]]
 
[[Category:Stub articles]]
 
[[Category:Stub articles]]
   
  +
{{GHCUsersGuide|glasgow_exts|multi-parameter-type-classes|a Multi Parameter Type Classes section}}
   
 
== About ==
 
== About ==
   
Basically, [[type]] [[class]]es which can take multiple arguments, such as:
+
Basically, [[type class|type classes]] which can take multiple arguments, such as:
   
<hask>
+
<haskell>
class Foo a b
+
class Monad m => VarMonad m v where
  +
new :: a -> m (v a)
</hask>
 
  +
get :: v a -> m a
  +
put :: v a -> a -> m ()
   
  +
instance VarMonad IO IORef where ...
Without [[functional dependencies]] or [[associated types]], these multi-parameter type classes may cause too much ambiguity to pass the type-checker.
 
  +
instance VarMonad (ST s) (STRef s) where ...
  +
</haskell>
  +
  +
To enable them, use the <hask>{-# LANGUAGE MultiParamTypeClasses #-}</hask> pragma.
  +
  +
If you think of a single-parameter type class as a set of types, then a multi-parameter type class is a relation between types.
  +
  +
Naive use of MPTCs may result in ambiguity, so [[functional dependencies]] were developed as a method of resolving that ambiguity, declaring that some subset of the parameters is sufficient to determine the values of the others.
  +
  +
Some uses of MPTCs with functional dependencies can be replaced with [[type families]].
  +
  +
The above example can even be implemented in
  +
[[Mutable variable|plain Haskell 98]].
   
 
== Also see ==
 
== Also see ==
   
[http://hackage.haskell.org/trac/haskell-prime/wiki/MultiParamTypeClasses The Haskell' page]
+
[http://prime.haskell.org/wiki/MultiParamTypeClasses The Haskell' page]

Revision as of 18:55, 4 April 2019


The GHC Users Guide has a Multi Parameter Type Classes section.

About

Basically, type classes which can take multiple arguments, such as:

class Monad m => VarMonad m v where
  new :: a -> m (v a)
  get :: v a -> m a
  put :: v a -> a -> m ()

instance VarMonad IO IORef where ...
instance VarMonad (ST s) (STRef s) where ...

To enable them, use the {-# LANGUAGE MultiParamTypeClasses #-} pragma.

If you think of a single-parameter type class as a set of types, then a multi-parameter type class is a relation between types.

Naive use of MPTCs may result in ambiguity, so functional dependencies were developed as a method of resolving that ambiguity, declaring that some subset of the parameters is sufficient to determine the values of the others.

Some uses of MPTCs with functional dependencies can be replaced with type families.

The above example can even be implemented in plain Haskell 98.

Also see

The Haskell' page