繁体   English   中英

在元组列表中交换元组

[英]Swapping tuples in a list of tuples

我试图编写一个能够在这样的元组列表中交换元组的代码:[(“ a”,“ b”),(“ c”,“ d”)]-> [(“ b”, “A”),( “d”, “C”)]

tupleXTurn :: [(String,String)]->[(String,String)]
tupleXTurn (x:xs) = (snd x,fst x) ++ (tupleXTurn xs)

类型对应的错误。 非常感谢!

错误是:

Couldn't match type ‘xs’ with ‘String’
  ‘xs’ is a rigid type variable bound by
       an expression type signature: tupleXTurn xs
       at ZinkeMarencicUebung08.hs:42:21
Expected type: (xs, String)
  Actual type: (String, String)
In the first argument of ‘fst’, namely ‘x’
In the expression: fst x

快速解决

更换:

(snd x,fst x) ++ (tupleXTurn xs)

有:

(snd x,fst x) : (tupleXTurn xs)

运算符(++)用于连接两个列表。 要在列表前添加元素,应使用(:)

您还应该注意,您的函数无法与函数定义中的[]匹配。 因此,您应该具有:

tupleXTurn :: [(String, String)]->[(String, String)]
tupleXTurn [] = []
tupleXTurn (x:xs) = (snd x,fst x) : (tupleXTurn xs)

现场演示

改善功能

您还可以将函数类型放宽为:

[(a, b)] -> [(b, a)]

最后,您可以简单地根据mapswap定义函数(来自Data.Tuple ):

tupleXTurn :: [(a, b)]->[(b, a)]
tupleXTurn = map swap

现场演示

该错误是因为您试图用++连接一个元组和一个列表。 当您要将两个列表连接在一起,但又想在列表的前面添加一个元素时,可以使用此方法,因此应使用:运算符:

tupleXTurn (x:xs) = (snd x, fst x) : tupleXTurn xs

更惯用的方式是定义一个函数以交换单个元组,然后使用map

swap :: (a, b) -> (b, a)
swap (a, b) = (b, a)

tupleXTurn :: [(String, String)] -> [(String, String)]
tupleXTurn xs = map swap xs

这也避免了必须处理空列表的问题,到目前为止,如果给定一个空列表作为参数,由于与模式(x:xs)不匹配,则函数也会出错,但是map已经处理了该问题您。

仅供参考: swap已经在Data.Tuple定义,因此您甚至不需要自己定义它。

暂无
暂无

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

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