I’m trying to sort a list and to check my sorting algorithm is working as I would expect I would like to print out specific elements of the sorted list, something I would expect to be a simple task but is proving to be very difficult – I guess I’m going about it the wrong way.
data Candidate = Candidate Float Float Float String
…
getName :: Candidate -> String
getName (Candidate weight profit effic name) = name
…
main = do
let items = [Candidate 0.20 4.17 (calculateEfficiency 0.20 4.17) "Weapon"]
Candidate 3.11 4.53 (calculateEfficiency 3.11 4.53) "Tinned food":items
Candidate 1.04 4.64 (calculateEfficiency 1.04 4.64) "Ammunition":items
Candidate 2.70 1.19 (calculateEfficiency 2.70 1.19) "Water":items
let sortedItems = sortBy mySort items
putStrLn (getName (sortedItems !! 0))
The error I get is:
Couldn't match expected type `[b0]' with actual type `IO ()'
In the return type of a call of `putStrLn'
In the expression: putStrLn (getName (sortedItems !! 0))
In the expression:
do { let items = ...;
Candidate 3.11 4.53 (calculateEfficiency 3.11 4.53) "Tinned food"
: items;
Candidate 1.04 4.64 (calculateEfficiency 1.04 4.64) "Ammunition"
: items;
Candidate 2.7 1.19 (calculateEfficiency 2.7 1.19) "Water" : items;
.... }
Failed, modules loaded: none.
Thanks for any help.
The
:operator is the prepend operator for lists, but it doesn’t actually modify a list. Imagine that instead of a list, you had a number; what you are doing is equivalent to this:That does’t make any sense.
You need to store the result of the prepend somewhere. You can do this by either creating new variables for each step:
…or you can simply create a long list to begin with:
This should yield the expected results, depending on if you also implemented
mySortcorrectly.