简体   繁体   English

在元组列表中交换元组

[英]Swapping tuples in a list of tuples

I tried to write a code which is capable of swapping tuples in a list of tuples like that: [("a","b"),("c","d")] --> [("b","a"),("d","c")] 我试图编写一个能够在这样的元组列表中交换元组的代码:[(“ a”,“ b”),(“ c”,“ d”)]-> [(“ b”, “A”),( “d”, “C”)]

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

There's an error corresponding the types. 类型对应的错误。 Thanks alot! 非常感谢!

The Error is: 错误是:

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

Quick fix 快速解决

Replace: 更换:

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

with: 有:

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

Operator (++) is for concatenating two lists. 运算符(++)用于连接两个列表。 For prepending an element to a list you should use (:) . 要在列表前添加元素,应使用(:)

You should also notice that your function is not able to match [] in your function definition. 您还应该注意,您的函数无法与函数定义中的[]匹配。 So you should have: 因此,您应该具有:

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

Live demo 现场演示

Improving the function 改善功能

You can also relax the function type to: 您还可以将函数类型放宽为:

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

And finally, you can simply define your function in terms of map and swap (from Data.Tuple ): 最后,您可以简单地根据mapswap定义函数(来自Data.Tuple ):

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

Live demo 现场演示

The error is because you're trying to concatenate a tuple and a list with ++ . 该错误是因为您试图用++连接一个元组和一个列表。 This is used when you want to join two lists together, but you want to prepend an element to the front of the list, so you should use the : operator instead: 当您要将两个列表连接在一起,但又想在列表的前面添加一个元素时,可以使用此方法,因此应使用:运算符:

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

A more idiomatic way would be to define a function to swap a single tuple then use map : 更惯用的方式是定义一个函数以交换单个元组,然后使用map

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

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

This also avoids the problem of having to handle the empty list, as of right now your function would also error if given an empty list as its argument since it doesn't match the pattern (x:xs) , but map already handles this for you. 这也避免了必须处理空列表的问题,到目前为止,如果给定一个空列表作为参数,由于与模式(x:xs)不匹配,则函数也会出错,但是map已经处理了该问题您。

FYI: swap is already defined in Data.Tuple , so you don't even need to define it yourself. 仅供参考: swap已经在Data.Tuple定义,因此您甚至不需要自己定义它。

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

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