Pairing adjacent list items in Haskell

前端 未结 3 628
情话喂你
情话喂你 2020-12-16 00:55

I have a chained list like

[\"root\", \"foo\", \"bar\", \"blah\"]

And I\'d like to convert it to a list of tuples, using adjacent pairs. Li

3条回答
  •  长情又很酷
    2020-12-16 01:34

    Okay, here's the comment as an answer:

    Just zipAdj x = zip x $ tail x will suffice. zip stops upon reaching the end of the shorter of the two lists, so this simply pairs each item in the list with its successor, which seems to be all you want.

    And for the sake of explaining the pointless version: zip <*> tail uses the Applicative instance for "functions from some type", which basically amounts to a lightweight inline Reader monad--in this case the list is the "environment" for the Reader. Usually this just obfuscates matters but in this case it almost makes it clearer, assuming you know to read (<*>) here as "apply both of these to a single argument, then apply the first to the second".

提交回复
热议问题