3

I am trying to implement something like this:

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

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

i know this code is wrong but its just the idea. How can i concat the rest of values with the min value that return the recursion. input will be like

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]

3 Answers 3

6

I think you are trying to implement selection sort.

It is better for mymin to return the minimum element along with rest of the elements of the list.

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
Sign up to request clarification or add additional context in comments.

1 Comment

@Urah No, you don't need to. a is just any type which belong to typeclass Ord. It is just to make your function polymorphic over Ord class. But it is better practice to write types before writing function definitions. Also by writing types you can provide compiler with certain hints with which it can perform certain kind of optimizations.
2

You need to remove the first occurence of the min from your list and concat it to the front of the rest

mymin :: (Ord a) => [a] -> a
mymin [x] = x 
mymin (x:y:xs) | x < y     = mymin (x:xs)
               | otherwise = mymin (y:xs)

myremove :: (Eq a) => a -> [a] -> [a] 
myremove x []  = [] 
myremove x (y:ys) | x == y    = ys
                  | otherwise = y: myremove x ys 

mysort :: (Ord a) => [a] -> [a] 
mysort []  = [] 
mysort [x] = [x] 
mysort xs  = x : mysort (myremove x xs) where x = mymin xs

Comments

0

Building on Satvik's answer, you could avoid explicit recursion by writing mymin as

mymin :: Ord a => [a] -> (a, [a])
mymin (x : xs) = foldr f (x, []) xs where
  f z (y, ys) = if y < z then (y, z : ys) else (z, y : ys)        

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.