简体   繁体   中英

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]

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM