Amir Nabaei
Amir Nabaei

Reputation: 1642

change elements in a list in Haskell

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]

Upvotes: 1

Views: 1459

Answers (2)

bheklilr
bheklilr

Reputation: 54058

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

Upvotes: 2

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476659

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.

Upvotes: 1

Related Questions