rem208
rem208

Reputation: 79

function adds an element to an list and returned sorted

I am trying to write a function where it takes an element and an list and add it to it as long as the list sorted (the smaller to grater) and then sort it again and return it, so I did the function with help of "quickSort" where I sort the list and "isSorted" where is check if a list Is sorted.

so the function first check if the list is sorted if yes it adds the element to it and then after adding it to the list, the list get sorted and returned.

insert::a->[a]->[a]
insert n xs 
          | isSorted xs == True = n : xs
insert n xs = quicksort xs


quicksort :: (Ord a) => [a] -> [a]  
quicksort [] = []  
quicksort (x:xs) =   
    let smallerSorted = quicksort [a | a <- xs, a <= x]  
        biggerSorted = quicksort [a | a <- xs, a > x]  
    in  smallerSorted ++ [x] ++ biggerSorted  


isSorted :: (Ord a) => [a] -> Bool
isSorted []       = True
isSorted [x]      = True
isSorted (x:y:xs) = x <= y && isSorted (y:xs)

I got this error

main.hs:59:13: error:
    * No instance for (Ord a) arising from a use of `isSorted'
      Possible fix:
        add (Ord a) to the context of
          the type signature for:
            insert :: forall a. a -> [a] -> [a]
    * In the first argument of `(==)', namely `isSorted xs'
      In the expression: isSorted xs == True
      In a stmt of a pattern guard for
                     an equation for `insert':
        isSorted xs == True
   |
59 |           | isSorted xs == True = n : xs
   |             ^^^^^^^^^^^

Upvotes: 1

Views: 51

Answers (1)

Fyodor Soikin
Fyodor Soikin

Reputation: 80805

isSorted requires that its type parameter a has an instance of the Ord type class. That's how it compares the elements.

Since insert calls isSorted, insert must also require that a has an instance of the Ord class, so that it can pass that instance to isSorted for comparing the elements:

insert :: Ord a => a->[a]->[a]

Upvotes: 4

Related Questions