문제

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.

도움이 되었습니까?

해결책

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top