I’m working through Bartosz Milewski’s excellent series on category theory for programmers. Category theory is a set of concepts that helps to drive Haskell’s design. These are my responses to the challenge questions.

Part 1: Composition

1.1 Implement, as best as you can, the identity function in your favorite language (or the second favorite, if your favorite language happens to be Haskell).

id <- function(x) x

# This identity works for simple 1:1 functions
square <- function(x) x^2
id(square(3))
## [1] 9
square(id(3))
## [1] 9
# It can nest functions as long as the output one argument
multiply <- function(a, b) a*b
id(multiply(2, 7))
## [1] 14
# But it fails to pass forward multiple arguments gracefully
tryCatch(
  multiply(id(2, 7)),
    error = function(e) 
  {
    print(e$message)
  }
)
## [1] "unused argument (7)"

1.2 Implement the composition function in your favorite language. It takes two functions as arguments and returns a function that is their composition.

compose <- function(a, b) function(...) a(b(...))
compose(square, square)(2)
## [1] 16
compose(square, multiply)(2, 3)
## [1] 36

1.3 Write a program that tries to test that your composition function respects identity.

Don’t know how to approach this one.

1.4 Is the world-wide web a category in any sense? Are links morphisms?

The world wide web is a category because it consists of objects, pages, connected by arrows, links. These links can be composed. If yahoo links to facebook and facebook links to google then we can navigate from yahoo to google.

Links are morphisms only in a very ordinary sense. They point from pages to pages always. A more sophisticated morphism would require a more diverse set of objects. For example we could consider that pages can link you to people and people can link you to pages.

1.5 Is Facebook a category, with people as objects and friendships as morphisms?

Yes.

1.6 When is a directed graph a category?

Always.