git.iko.soy/rowtype-yoga/purescript-native
on d68d1ea help sign in
48 lines 1.7 kB history raw
1Type Classes
2============
4PureScript has basic support for type classes via the ``class`` and ``instance`` keywords.
6Types appearing in class instances are must be of the form ``String``, ``Number``, ``Boolean``, or ``C t1 ... tn`` where ``C`` is a type constructor (including ``[]`` and ``->`` and ``t_i`` are types of the same form).
8Type class instances are resolved based on the order in which they appeared in the source files. Overlapping instances will result in a compilation error.
10Example
11-------
13Here is an example of the ``Show`` typeclass, with instances for ``String``, ``Booleans`` and ``[]``::
15 class Show a where
16 show :: a -> String
18 instance showString :: Show String where
19 show s = s
21 instance showBoolean :: Show Boolean where
22 show true = "true"
23 show false = "false"
25 instance showArray :: (Show a) => Show [a] where
26 show [] = "[]"
27 show (x:xs) = show x ++ " : " ++ showArray xs
29 example = show [true, false]
31Superclasses
32------------
34Superclass implications can be indicated in a class declaration with a backwards fat arrow ``<=``::
36 class (Monad m) <= MonadFail m where
37 fail :: forall a. String -> m a
39Superclass instances will be used when searching for an instance of a subclass. For example, in the code below, the ``Monad`` constraint introduced by the ``return`` function can be discharged since ``Monad`` is a superclass of ``MonadFail``::
41 assert :: forall m. (MonadFail m) => Boolean -> m Unit
42 assert true = return unit
43 assert false = fail "Assertion failed"
45Type Annotations
46----------------
48A constrained type will never be inferred for a top-level declaration without an explicit type signature.