Search code examples
haskellhappstack

Deriving PathInfo class in web routes?


I am reading the web-routes tutorial in Happstack, and I have no idea what this is doing:

$(derivePathInfo ''Sitemap)

class PathInfo a where
  toPathSegments :: a -> [String]
  fromPathSegments :: URLParser a

The doc simply says:

we use template-haskell to derive an instance of PathInfo for the Sitemap type.

but where does it "store" it? I thought haskell had no state, and is PathInfo our own thing, or is it part of happstack?

If someone could explain this, for dummies? Thanks.


Solution

  • It generates the code that defines an instance of the PathInfo class for the Sitemap type. This isn't "state" as much as "type-global constants". For example, toPathSegments (Article (ArticleId 5)) will return something like ["Article", "5"] which in turn will be used to generate a URL like "/Article/5". The other function, fromPathSegments, is the inverse operation, parsing "/Article/5" back into Article (ArticleId 5).

    You could write this instance manually:

    instance PathInfo Sitemap where
        toPathSegments Home = ["Home"]
        toPathSegments (Article (ArticleId x)) = ["Article", show x]
        fromPathSegments = ...
    

    Template Haskell is only used to reduce the need for this boilerplate code.

    You might like to read the chapter on type classes in the book Learn You a Haskell for Great Good! which is aimed at Haskell beginners.