简体   繁体   中英

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")]

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 ):

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 :

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.

FYI: swap is already defined in Data.Tuple , so you don't even need to define it yourself.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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