Haskell 将列表展开为路径

Haskell 将列表展开为路径,haskell,Haskell,我有这样一份清单: input = [[1,1], [3,3], [5,5], [7,7]] > map (\i -> [input!!i, input!!(i+1)]) [0 .. length input-2] [[[1,1],[3,3]],[[3,3],[5,5]],[[5,5],[7,7]]] 我想要这个输出: [[[1,1],[3,3]],[[3,3],[5,5]],[[5,5],[7,7]]] (目标是让路径由边组成,[1,1]-[3,3],[3,3]-[5,5]

我有这样一份清单:

 input = [[1,1], [3,3], [5,5], [7,7]]
> map (\i -> [input!!i, input!!(i+1)]) [0 .. length input-2]
[[[1,1],[3,3]],[[3,3],[5,5]],[[5,5],[7,7]]]
我想要这个输出:

[[[1,1],[3,3]],[[3,3],[5,5]],[[5,5],[7,7]]]
(目标是让路径由边组成,
[1,1]-[3,3],[3,3]-[5,5],[5,5]-[7,7]
…顺便说一句,这个问题是重复的,我不会感到惊讶。)

我可以得到如下输出:

 input = [[1,1], [3,3], [5,5], [7,7]]
> map (\i -> [input!!i, input!!(i+1)]) [0 .. length input-2]
[[[1,1],[3,3]],[[3,3],[5,5]],[[5,5],[7,7]]]

你们有更干净的解决方案吗?肯定有更干净的东西。

你可以用它的尾巴
zip
input
来获得元组列表:

Prelude> zip input $ tail input
[([1,1],[3,3]),([3,3],[5,5]),([5,5],[7,7])]
从那里,如果需要,可以编写一个函数,用每个元组生成一个列表,例如

tupleToList :: (t, t) -> [t]
tupleToList (x, y) = [x, y]
这使您能够映射压缩列表:

Prelude> fmap tupleToList $ zip input $ tail input
[[[1,1],[3,3]],[[3,3],[5,5]],[[5,5],[7,7]]]

请注意,
tail
是不安全的,因为如果原始列表为空,它会引发异常。

tail
是不安全的,但是
zip-xs(tail-xs)
是安全的。如果您希望它甚至是本地安全的(不需要跨过程的正确性参数),您可以用
drop 1
@DanielWagner替换
tail
,确实如此!我甚至没有意识到这一点。谢谢你指出:)我总是忘记
zip x y
不需要
length x==length y
let xs = [[1,1], [3,3], [5,5], [7,7]] in zipWith (\a b -> [a,b]) xs (tail xs)
-- [[[1,1],[3,3]],[[3,3],[5,5]],[[5,5],[7,7]]]