Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading