1

I am trying to implement a very trivial sorting algorithm in Haskell. It compiles but keeps giving me incorrect outputs.

Here is the code

import Data.List

minimum' :: (Ord a) => [a] -> a
minimum' (x:xs) = foldr (\ x y -> if x <= y then x else y) x xs

qsrt :: (Ord a) => [a] -> [a]
qsrt [] = []
qsrt l@(x:xs) = minimum' l : qsrt xs

Any thoughts?

7
  • 1
    What leads you to believe that qsrt would sort the list? Which sorting algorithm are you trying to implement? Commented Jul 1, 2015 at 18:53
  • Well, I am only a novice. My thinking was, if I pattern match on (x:xs) extract the smallest element of that list and cons it with a recursion on the same function of the tail of the list I would eventually end up with a sorted list.. But the logic is clearly incorrect. None in particular. Just refactoring some functions myself for academic purposes. Commented Jul 1, 2015 at 18:55
  • 1
    qsrt takes the minimum element of l and then skips x, but x would only be the minimum element of l by accident so you're usually skipping the wrong element. Commented Jul 1, 2015 at 18:55
  • Doesnt l@(x:xs) represent the entire list? Commented Jul 1, 2015 at 18:57
  • 1
    You're probably trying to implement selection sort. Try let qsrt [] = []; qsrt l = let y = minimum' l in y : qsrt (delete y l) Commented Jul 1, 2015 at 19:04

2 Answers 2

6

The logic error is that qsrt takes the minimum element of l and then skips x, but x would only be the minimum element of l by accident so you're usually skipping the wrong element.

Sign up to request clarification or add additional context in comments.

Comments

1

Just as an addendum to Rein Henrichs's answer, I managed to craft a correct version of the above using a filter.

import Data.List

minimum' :: (Ord a) => [a] -> a
minimum' (x:xs) = foldl' (\ x y -> if x <= y then x else y) x xs

srt :: (Ord a) => [a] -> [a]
srt [] = []
srt l = ml : srt (delete ml l)
    where ml = minimum' l

2 Comments

This will give wrong results if the list contains duplicate elements.
@Franky Thanks for pointing it out. It should work as intended now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.