user2876457
user2876457

Reputation: 47

Swapping Pairs in Haskell

So i've got this function to swap pairs of numbers in haskell, and i don't know what i've done wrong, maybe you guys can give me a hand. SO basically this function gets a list, say, [1,2,3,4,5], and returns the numbers swapped by pairs, something like, [2,1,4,3,5]. if the number of elements is odd, the last element stays the same.

Here's what i've done:

swapPairs :: [a] -> [a]
swapPairs (x:xs) = [!!x = !!x+1 && !!x+1 = !!x| x <- xs]

Upvotes: 1

Views: 1064

Answers (2)

Jens Erat
Jens Erat

Reputation: 38682

-- Return first two elements in inverted order, recusively call for remaining list,
-- only matches lists of two or more elements
swapPairs (a:b:xs) = b : a : swapPairs xs
-- Return tail for zero or one remaining elements
swapPairs (xs)     = xs

Upvotes: 5

Artem Sobolev
Artem Sobolev

Reputation: 6069

You can use pattern matching to fetch 2 head elements:

swapPairs (x:y:xs) = y : x : (swapPairs xs)

Upvotes: 2

Related Questions