我正在尝试实现这样的东西:

mymin (x:[]) = x
mymin (x:y:xs) = mymin ((if x < y then x else y):xs)

mysort [] = []
mysort (x) = mymin x (mysort othervalues)

我知道这段代码是错误的,但这只是想法。我如何将其余值与返回递归的最小值连接起来。
输入将像

mysort [7,9,3,7,1,2]
[1,**7,9,3,7,2**]
[1,2,**7,9,3,7**]
[1,2,3,**7,9,7**]
[1,2,3,7,**7,9**]
[1,2,3,7,7,**9**]
[1,2,3,7,7,9]

最佳答案

我认为您正在尝试实现选择排序。
mymin 最好与列表中的其余元素一起返回最小元素。

mymin :: Ord a => [a] -> (a,[a])
mymin [x] = (x,[])
mymin (x:xs) = let (min,rest) = mymin xs
    in if x < min then (x,min:rest) else (min,x:rest)

mysort :: Ord a => [a] -> [a]
mysort [] = []
mysort xs = let (min,rest) = mymin xs
    in min:mysort rest

关于haskell - 递归 Haskell,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13797428/

10-11 20:10