简体   繁体   中英

Could not deduce error type

we have to write a code, which will sort the elments of a list.

For this , we have to use two help functions. In my case calculate (gives the max/min of a list) and delete ( will delete the max/min).

And what a suprise, it is not working ;).

Running the code , I am always getting:" could not deduce (Ey (a-> a-> Bool)) arising from a use of 'sort'"

Any suggestions?

sort p [] = []
sort p ls = selected : sort p (delete)
 where
  selected =  calculate p ls
  calculate p ls
                | p == < =  minimum ls
                | otherwise = maximum ls
  delete = del selected ls
  del selected ls = filter (/= selected) ls

Here is a version that should be close to your idea (taking the least element of the list and then sorting the rest):

import Data.List (delete)

sort :: Ord t => [t] -> [t]
sort [] = []
sort ls = selected : sort (delete selected ls)
 where selected = minimum ls

that will not shorten a list:

λ> sort [2,4,6,1,2,5]
[1,2,2,4,5,6]

the idea to take in a function to decide if you want to sort descending or ascending can be done like this:

import Data.List (delete, minimumBy)
import Data.Function (on)

sort :: Eq t => (t -> t -> Ordering) -> [t] -> [t]
sort _ [] = []
sort p ls = selected : sort p (delete selected ls)
 where selected = minimumBy p ls

example:

λ> sort (compare) [2,4,6,1,2,5]
[1,2,2,4,5,6]
λ> sort (compare `on` negate) [2,4,6,1,2,5]
[6,5,4,2,2,1]

of course this is not really a good sorting-algorithm


now you should go over your version again and think how you can fix it - for example there is a way to use maximum to get the list sorted descending instead


using (<) and (>) :

the idea is then to basically rewrite minimum and use the compare function you pass on:

import Data.List (delete, foldr1)

sort :: Eq t => (t -> t -> Bool) -> [t] -> [t]
sort _ [] = []
sort p ls = extremum : sort p (delete extremum ls)
  where extremum  = foldr1 (\ a b -> if p a b then a else b) ls

example:

λ> sort (<) [2,4,6,1,2,5]
[1,2,2,4,5,6]
λ> sort (>) [2,4,6,1,2,5]
[6,5,4,2,2,1]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM