繁体   English   中英

我 go 如何交换 Haskell 列表列表中每个列表的前两个元素?

[英]How would I go about swapping the first two elements of every list in a list of lists in Haskell?

我想创建一个 function 来交换列表列表中每个列表的前两个元素

例如:

swapElems [[1], [1,3]] == [[1],[3,1]]

或者

swapElems ["apple", "pear", "banana"]  == ["paple","epar","abnana"]

到目前为止,我已经尝试过:

swapElems [(x:y:xs),(z:u:zs),(t:i:ts)] = [(y:x:xs),(u:z:zs),(i:t:ts)]
swapElems [(x:y:xs),(z:u:zs)] = [(y:x:xs),(u:z:zs)]
swapElems [(x:y:xs)] =[(y:x:xs)]
swapElems [] = []

但这仅在我输入恰好包含 1 个或 2 个或 3 个列表的列表列表时有效。

我需要一个适用于任意数量列表的解决方案。 我怎样才能以某种方式重写它,以便无论我包含多少列表,它都能正常工作。

我首先编写一个 function 交换单个列表的两个第一个元素,例如:

swapTwoFirst (x:y:xs) = (y:x:xs)
swapTwoFirst xs = xs

然后:

swapElems = map swapTwoFirst

暂无
暂无

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

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