Home > database >  What do I have to add to my Haskell code to work for all of the cases?
What do I have to add to my Haskell code to work for all of the cases?

Time:10-17

My code is not working for example : swapElems ([],[1,2]) How can I fix it ?

swapElems :: [[a]] -> [[a]]
swapElems [] = []
swapElems [x:y:xs] = [y : x :xs]
swapElems ((x:y:s):ls) = (y:x:s): swapElems ls
swapElems [x]= [x]

CodePudding user response:

Your pattern matching does too much. You can work with three patterns:

  1. the empty list;
  2. a non-empty list where the first sublist has two or more items; and
  3. a non-empty list where the first list has less than two items.

You can thus define this as:

swapElems :: [[a]] -> [[a]]
swapElems [] = …  -- (1)
swapElems ((x:y:xs):xss) = …  -- (2)
swapElems (xs:xss) = …  -- (3)

It probably however makes more sense to implement a helper function:

swap2 :: [a] -> [a]
swap2 (x:y:xs) = …
swap2 xs = xs

and then work with a mapping of swap2:

swapElems :: [[a]] -> [[a]]
swapElems = map swap2
  • Related