Skip to main content Accessibility help
Internet Explorer 11 is being discontinued by Microsoft in August 2021. If you have difficulties viewing the site on Internet Explorer 11 we recommend using a different browser such as Microsoft Edge, Google Chrome, Apple Safari or Mozilla Firefox.

Chapter 18: Higher-Order Types

Chapter 18: Higher-Order Types

pp. 249-264

Authors

, Yale University, Connecticut
  • Add bookmark
  • Cite
  • Share

Summary

All of the types considered thus far have been first order. For example, the type constructor Tree has always been paired with an argument, as in Tree Int (a tree containing Int values) or Tree a (representing the family of trees containing a values). But Tree by itself is a type constructor: something that takes a type as an argument and returns a type as a result. There are no values in Haskell that have this type, but such “higher-order” types can be used in class declarations in useful ways, as we shall see in this chapter.

The Functor Class

To begin, consider the following Functor class defined in the Standard Prelude:

class Functor f where

fmap :: (ab) → f af b

DETAILS

Type applications are written in the same manner as function applications, and are also left associative: The type T a b is equivalent to ((T a) b).

There is something new here. The type variable f is applied to other types, as in f a and f b. Thus, we would expect f to be a type such as Tree, which can be applied to an argument. Indeed, a suitable instance of Functor for type Tree would be:

instance Functor Tree where

fmap f (Leaf x) = Leaf (f x)

fmap f (Branch t1 t2) = Branch (fmap f t1) (fmap f t2)

Recall that in Section 7.2 we defined a function mapTree that behaved just as the above fmap method, so we could have instead written:

instance Functor Tree where

fmap = mapTree

Such an instance declaration declares that Tree, rather than Tree a, is an instance of Functor.

Note that in Haskell we write Tree Int for trees of integers, and we say that Tree is a type constructor. And we write [Int] for lists of integers. However, what is the type constructor for lists? Because of Haskell's special syntax for the list data type, there is also a special syntax for its type constructor, namely [].

About the book

Access options

Review the options below to login to check your access.

Purchase options

eTextbook
US$79.00
Hardback
US$182.00
Paperback
US$79.00

Have an access code?

To redeem an access code, please log in with your personal login.

If you believe you should have access to this content, please contact your institutional librarian or consult our FAQ page for further information about accessing our content.

Also available to purchase from these educational ebook suppliers