从Haskell中的列表中打印元素

时间:2012-03-28 13:26:19

标签: list sorting haskell printing ghci

我正在尝试对列表进行排序并检查我的排序算法是否正常工作,因为我希望我能打印出排序列表中的特定元素,我希望这是一个简单的任务,但事实证明是非常困难 - 我想我的方式错了。

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))

我得到的错误是:

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.

感谢您的帮助。

1 个答案:

答案 0 :(得分:12)

:运算符是列表的前置运算符,但它实际上并不修改列表。想象一下,你有一个数字,而不是一个列表;你在做什么等同于:

let items = 1
2 + items
7 + items
3 + items

这没有任何意义。

你需要存储前置的结果。您可以通过为每个步骤创建新变量来执行此操作:

let items = [Candidate 0.20 4.17 (calculateEfficiency 0.20 4.17) "Weapon"]
let items2 = Candidate 3.11 4.53 (calculateEfficiency 3.11 4.53) "Tinned food" : items

...或者你可以简单地创建一个长列表:

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"
            , Candidate 1.04 4.64 (calculateEfficiency 1.04 4.64) "Ammunition"
            ]

这应该会产生预期的结果,具体取决于您是否也正确实施了mySort