简体   繁体   English

来自haskell列表的连续n元组

[英]Consecutive n-tuples from a list in haskell

Is there an easy-ish / general way to get consecutive n-tuples?是否有一种简单/通用的方法来获得连续的 n 元组? For example:例如:

f3 [1,2,3,4,5,6] = [(1,2,3),(2,3,4),(3,4,5),(4,5,6)]
f4 [1,2,3,4,5,6] = [(1,2,3,4),(2,3,4,5),(3,4,5,6)]

Similar question however it only covers pairs (x,y) . 类似的问题但是它只涵盖对(x,y)

As @amalloy points out in the comments, there's no straightforward way to define this operation generally across different tuple sizes, but if you're just looking for a general pattern for writing a set of such functions, there are a few possibilities.正如@amalloy 在评论中指出的那样,没有直接的方法来定义通常跨不同元组大小的此操作,但是如果您只是在寻找编写一组此类函数的通用模式,则有几种可能性。

The simplest, though it looks a little physically repulsive, is just to write a simple recursive pattern match that spits out a tuple and then recurses on the tail of the argument, stopping as soon as the list becomes too short:最简单的,虽然看起来有点物理排斥,只是写一个简单的递归模式匹配,吐出一个元组,然后在参数的尾部递归,一旦列表变得太短就停止:

f3 :: [a] -> [(a,a,a)]
f3 (x1:nxt@(x2:x3:_)) = (x1,x2,x3):f3 nxt
f3 _ = []

f4 :: [a] -> [(a,a,a,a)]
f4 (x1:nxt@(x2:x3:x4:_)) = (x1,x2,x3,x4):f4 nxt
f4 _ = []

While you could generalize the solution you linked to for pairs by writing:虽然您可以通过编写以下内容来概括您为配对链接的​​解决方案:

f3' = zip3 <*> tail <*> tail.tail
f4' = zip4 <*> tail <*> tail.tail <*> tail.tail.tail

this is too clever by half and also not a particularly efficient solution, as every argument repeats the tail operations of the previous argument when the results could be reused.这太聪明了一半,也不是一个特别有效的解决方案,因为当结果可以重用时,每个参数都会重复前一个参数的尾部操作。

An alternative and probably reasonably approach is:另一种可能是合理的方法是:

f3'' str = let l1:l2:l3:_ = tails str in zip3 l1 l2 l3
f4'' str = let l1:l2:l3:l4:_ = tails str in zip4 l1 l2 l3 l4

though it relies on having the right zipk available.虽然它依赖于有正确的zipk可用。 While zip3 is defined in Prelude and zip4 through zip7 are defined in Data.List , if you need zip8 or more, you need to define it yourself.虽然zip3Prelude中定义, zip4zip7zip7中定义, Data.List如果您需要zip8或更多,则需要自己定义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM