Question

I want to check elements in a list then if they are bigger then the next one then swap their places. I can not go further than the code below

change [] =[]
change (x:xs) 
       | x > head xs = change (head xs : x : tail xs) 
       | otherwise = change xs  

main = do 
 print $ change [3,2,4] 
 -- expected [2,3,4]
Was it helpful?

Solution

There are 3 base cases that you need to consider: 1) an empty list, 2) a list with one element, and 3) a list with two or more elements. If you consider these three cases individually, the function is pretty easy to define:

change :: Ord a => [a] -> [a]
change [] = []
change (x:[]) = [x]
change (x1:x2:xs)
    | x1 > x2 = x2 : change (x1 : xs)
    | otherwise = x1 : change (x2 : xs)

EDIT As @kqr has pointed out, you can rearrange this into

change :: Ord a => [a] -> [a]
change (x1:x2:xs)
    | x1 > x2 = x2 : change (x1 : xs)
    | otherwise = x1 : change (x2 : xs)
change other = other

OTHER TIPS

Have you tried:

change [] =[]
change [x] = [x]
change (x:xs) 
       | x > head xs = (head xs) : change (x : tail xs) 
       | otherwise = x : (change xs)

You lose the head of the array in the otherwise case.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top