2

我正在寻找一种功能性的方法来实现这一点:

list = [a b c d e f]
foo(list, 3) = [[a d] [b e] [c f]]

一个潜在的解决方案是:

foo(list,spacing) = zip(goo(list,spacing))

例如,在哪里,

goo([a b c d e f],3) = [[a b c] [d e f]]

什么是foo并且goo通常被称为,所以我可以寻找现有的解决方案而不是重新发明轮子?

笔记:我没有试图用文字来解释,而是展示了一些希望更容易获得的例子。用于更广泛理解的任意语法。

4

3 回答 3

3

您可以使用分区

(partition 3 '[a b c d e f])
=> ((a b c) (d e f))

(partition 2 '[a b c d e f])
=> ((a b) (c d) (e f))

编辑:

(apply map list (partition 3 '[a b c d e f]))
=> ((a d) (b e) (c f))
于 2013-03-30T04:22:00.480 回答
1

我认为没有内置功能。这很容易实现。

我知道你不想实现,但其中一个标签是 Haskell,所以也许你想看看这个

 p :: Int -> [a] -> [[a]]
 p n xs = [  [x | (x ,y) <- ys , y `mod` n == i]  |  i <- [0 .. n - 1] ,  let ys = zip xs [0 .. ]]

这很实用。

于 2013-03-30T07:30:15.513 回答
1

Your goo function is drop with flipped arguments. Given that, you can implement foo almost like you say in your question:

let foo list spacing = zip list (drop spacing list)

This still doesn't exactly give the result you need though, but close:

Prelude> foo "abcdef" 3
[('a','d'),('b','e'),('c','f')]

EDIT:

Reading more carefully, your goo function is splitAt with flipped arguments. Given that, foo can be defined like this:

let foo list spacing = (uncurry zip) $ splitAt spacing list

Which is the same as:

let foo list spacing = let (left, right) = splitAt spacing list
                       in zip left right
于 2013-03-30T10:09:09.590 回答