Moggi documentation

Higher-kinded types

Advanced page. Read kinds first; this page builds on it.

A type parameter is usually a type with values: data Box a = Box a puts one a inside. A higher-kinded parameter is a type constructor instead — a parameter of kind Type -> Type, such as Maybe, List or Either String. The declaration then applies it: f a.

This is what lets one function work over many containers. map is not written once for lists and again for Maybe; it is a method of a class whose parameter is the container.

main :: IO ()
main = do
  putStrLn (show (map (\x -> x + 1) [1, 2, 3]))
  putStrLn (show (map (\x -> x + 1) (Just 1)))
  putStrLn (show (map (\x -> x + 1) (Right 1 :: Either String Int)))
[2,3,4]
Just 2
Right 2

map comes from Functor, whose parameter is f: the class declares map :: (a -> b) -> f a -> f b. The f is not “a type containing an a” in some loose sense; it is a constructor of kind Type -> Type, applied to a in the signature. Maybe, List, Either e and your own parameterized types all qualify.

Folds over a shape

Foldable abstracts the same way over “a container of as you can walk”. Its methods use t a, so any t of kind Type -> Type with an instance works:

total :: (Foldable t, Num a) => t a -> a
total = foldr (+) 0

main :: IO ()
main = do
  putStrLn (show (total [1, 2, 3]))
  putStrLn (show (total (Just 41)))
6
41

Traversable goes one step further and rebuilds the shape around effects; it is why traverse can turn a [Maybe a] into a Maybe [a] without a list-specific implementation.

Writing a class over a constructor

The pattern is the same for a class of your own: declare the parameter, use it applied, and give one instance per container.

class Container f where
  empty :: f a
  insert :: a -> f a -> f a

instance Container Maybe where
  empty = Nothing
  insert x _ = Just x

instance Container List where
  empty = []
  insert x xs = x : xs

pair :: Container f => f Int
pair = insert 1 (insert 2 empty)

main :: IO ()
main = do
  putStrLn (show (pair :: Maybe Int))
  putStrLn (show (pair :: List Int))
  putStrLn (show (map (\x -> x * 2) (pair :: List Int)))
Just 1
[1,2]
[2,4]

Two spelling details matter here:

Partial application

A constructor with two parameters becomes a Type -> Type constructor when applied to one. Either String is such a constructor, which is why it has a Functor instance and can be mapped over above. Your own types behave the same: with data Pair a b = Pair a b, Pair Int is a constructor of kind Type -> Type.

A type synonym is expanded before the instance is matched, so a synonym for a partially applied constructor is accepted in an instance head and is equivalent to writing the expansion.

Why it matters

Higher-kinded abstraction is what makes the library’s shape-generic functions possible:

Limits

Where next


Moggi compiles to PHP, the JVM and .NET. This site is generated from docs/ in the moggi-lang/moggi repository; the same pages are readable there as Markdown.