Haskell sort with operator

Viewed 105

I want to implement a function

> ssort (<) [2,8,4,6,3,9,7]
  [2,3,4,6,7,8,9]
> ssort (>) [2,8,4,6,2,6,7]
  [9,8,7,6,4,3,2]

first i think i should have detect the operator,this is how i do it,

ssort [] =[]
ssort op xs |op ==(<) = minVal : ssort rest
            |op ==(>) = maxVal : ssort rest1
    where minVal =minimum xs
          maxVal =maximum xs
          rest =delete minVal xs
          rest1 = delete maxVal xs

and it gives an error:"parse error on input ??'

so i do this,and it gives same error

ssort [] =[]
ssort op xs |op 4 5 ==True = minVal : ssort rest
            |op 4 5 ==False = maxVal : ssort rest1
    where minVal =minimum xs
          maxVal =maximum xs
          rest =delete minVal xs
          rest1 = delete maxVal xs

how can i solve the problem?Thanks for any help.

1 Answers

You can't compare functions, so op == (<) will always be rejected by the compiler.

The good news is that you don't have to detect what op actually is. You can instead assume that it provides meaningful results every time it is used.

From your code, it looks like you want to use some selection sort. For that you need a custom minimum function which takes op as an additional argument, and returns the minimum according to op. You could start by implementing that.

Note that, in the libraries, we already have minimumBy and sortBy that can be used with an arbitrary op. E.g., you could use something like

where minVal = minimumBy cmp xs
      cmp x y | op x y = LT
              | op y x = GT
              | otherwise = EQ
Related