在Haskell中配对相邻的列表项 [英] Pairing adjacent list items in Haskell

查看:158
本文介绍了在Haskell中配对相邻的列表项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个链式列表,如

  [root,foo,bar,blah] 

我想将它转换为使用相邻对的元组列表。像这样

  [(root,foo),(foo,bar),(bar ,blah)] 

目前,我正在使用它来执行此操作:

  zipAdj x = tail(zip(:x)(x ++ []))

但是,我不太喜欢这种方法。任何人都可以想出更好的方法吗?如果它很明显我很抱歉,我对Haskell相当新。

好的,这里是评论作为答案:



只需 zipAdj x = zip x $ tail x 即可。 zip 在到达两个列表中较短的列表末尾时停止,因此这只是将列表中的每个项目与其后继列表进行配对,这似乎是您想要的。 p>

为了解释无意义的版本: zip< *> tail 将 Applicative 实例用于某些类型的函数,这基本相当于一个轻量级的内联Reader monad - 在这种情况下,列表是读者的环境。通常这只是混淆了事情,但在这种情况下,它几乎变得更清楚,假设您知道在这里阅读(< *>)参数,然后将第一个应用到第二个。


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. Like so

[("root", "foo"), ("foo", "bar"), ("bar", "blah")]

At the moment, I'm using this to do it:

 zipAdj x = tail (zip ("":x) (x++[""]))

However, I don't really like this method. Can anyone think of a better way? If it's glaringly obvious I apologise, I'm fairly new to Haskell.

解决方案

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".

这篇关于在Haskell中配对相邻的列表项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆