我想检查列表中的元素,然后如果它们比下一个更大,然后交换它们的位置。我不能比下面的代码更进一步
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]
您需要考虑 3 种基本情况:1) 一个空列表,2) 一个包含一个元素的列表,以及 3) 一个包含两个或多个元素的列表。如果您分别考虑这三种情况,则该函数很容易定义:
change :: Ord a => [a] -> [a]
change [] = []
change (x:[]) = [x]
change (x1:x2:xs)
| x1 > x2 = x2 : change (x1 : xs)
| otherwise = x1 : change (x2 : xs)
编辑正如@kqr 所指出的,您可以将其重新排列为
change :: Ord a => [a] -> [a]
change (x1:x2:xs)
| x1 > x2 = x2 : change (x1 : xs)
| otherwise = x1 : change (x2 : xs)
change other = other
你有没有尝试过:
change [] =[]
change [x] = [x]
change (x:xs)
| x > head xs = (head xs) : change (x : tail xs)
| otherwise = x : (change xs)
在其他情况下,您会丢失数组的头部。