Home > OS >  How would I go about swapping the first two elements of every list in a list of lists in Haskell?
How would I go about swapping the first two elements of every list in a list of lists in Haskell?

Time:10-10

I would like to create a function that swaps the first two elements of every list in a lists of lists

So for example:

swapElems [[1], [1,3]] == [[1],[3,1]]

or

swapElems ["apple", "pear", "banana"]  == ["paple","epar","abnana"]

So far I have tried:

swapElems [(x:y:xs),(z:u:zs),(t:i:ts)] = [(y:x:xs),(u:z:zs),(i:t:ts)]
swapElems [(x:y:xs),(z:u:zs)] = [(y:x:xs),(u:z:zs)]
swapElems [(x:y:xs)] =[(y:x:xs)]
swapElems [] = []

But this only works when I input a list of lists that contains exactly 1 or 2 or 3 lists.

I would need a solution that works for any number of lists. How could I rewrite it in a way so it works regardless of how many lists I include.

CodePudding user response:

I'd start with writing a function that swaps two first elements of a single list, e.g:

swapTwoFirst (x:y:xs) = (y:x:xs)
swapTwoFirst xs = xs

and then:

swapElems = map swapTwoFirst
  • Related