Search code examples
listhaskellpattern-matchingparse-error

Haskell syntax error in my function


I have tried to write a function that takes a list pair, and swaps the pair elements

inverse :: [(a,b)] -> [(b,a)]
inverse [] = []
inverse (x,y):xs = (y:x): inverse xs

I have loaded this function via Prelude, it gives me following error:

mydefs.hs:11:1: Parse error in pattern: inverse

This is line 11, inverse (x,y):xs = (y:x): inverse xs


Solution

  • You just have to surround the unpacked tuple and the rest of the list, like this

    inverse ((x, y):xs) = (y, x) : inverse xs
    

    Apart from this, you can use the Data.Tuple package's swap function, like this

    Prelude> import Data.Tuple
    Prelude Data.Tuple> map swap [(1, 2), (3, 4)]
    [(2,1),(4,3)]