quicksort orderby id asc
How can I use quicksort开发者_运维知识库 to orderby ID ascending on the list and then show elements ? I have error: No instance for (Ord FigureType). My code is:
showRectangles [] = "No rectangles"
showRectangles x = concat (map showRectangle (qsort x))
showRectangle :: FigureType -> String
showRectangle (Figure id width height) = "id: " ++ show id ++ " width: " ++ show width ++ " height: " ++ show height ++ "\n";
data FigureType = Figure Int Int Int deriving(Show, Read)
qsort [] = []
qsort (x:xs) = qsort (filter (< x) xs) ++ [x] ++ qsort (filter (>= x) xs)
You need to make FigureType
comparable. The simplest thing to do is to make it derive Eq
and Ord
.
data FigureType = Figure Int Int Int deriving(Show, Read, Ord, Eq)
BTW, there is already a sort
function in Data.List.
The short answer is that it don't know what <
and >=
means. You haven't told haskell that in that program.
To solve this, you must make an instance Ord FigureTye
. I assume you've seen the syntax before. If not, you can look for haskell type classes. Since Ord
is a subclass of Eq
, you must also create the instance Eq
for FigureType
, however, this can just be derived by using deriving(Show, Read, Eq)
. You could also write deriving(Show, Read, Eq, Ord)
. But the auto-generated instance for Ord
is probably not the implementation you have in mind.
Here is a link with the Ord
typeclass, it says what minimal amount of functions you have to implement. http://hackage.haskell.org/packages/archive/base/latest/doc/html/Prelude.html#t:Ord
Here is Real world haskells chapter on type-classes. It doesn't cover any instance of Ord
however. http://book.realworldhaskell.org/read/using-typeclasses.html
精彩评论