Using monads for trivial tasks like list manipulation?

前端 未结 6 1401
栀梦
栀梦 2021-02-09 05:13

Whenever I read about Monad example, they always present IO as a case study.

Are there any examples of monads doing list manipulation which somebody could present? I apr

6条回答
  •  别跟我提以往
    2021-02-09 06:04

    A nice example for list manipulation is querying an HTML/XML document, a la jQuery. jQuery is a monad. Let's examine an example:

    $(doc).find('> body')
          .find('> *')
          .is('table')
          .is('.bar')
          .find('> caption')
          .text()
    

    This gives you the captions of all the top-level tables having a CSS class bar. This is an unusual way to use jQuery (usually you'd simply do body > table.bar > caption), but that's because I wanted to show the steps.

    In xml-conduit you do it similarly:

    child cursor >>= element "body" >>= child
            >>= element "table" >=> attributeIs "class" "bar"
            >>= child >>= element "caption"
            >>= descendants >>= content
    

    What the list monad does is combine the steps. The monad in itself knows nothing about HTML/XML.

    In HXT you do it in almost the same way. Newer HXT versions use what are called arrows instead of monads, but the underlying principle is the same.

提交回复
热议问题