Haskell Prelude.head错误,空列表

时间:2013-03-08 02:00:36

标签: haskell functional-programming

我的代码抛出一个空列表错误。我跑的时候:

makeAgent :: Agent -> [Agent] -> Agent
makeAgent (Agent func n _) agents = (Agent func (n++(show $ length $ sameNames n agents)) empty) --appends number to name to differentiate agents
    where sameNames n agents = filter (findName n) agents
          findName n1 (Agent _ n2 _) = (slice 0 3 n1) == (slice 0 3 n2) --ignore the suffix
          empty = head $ getEmpty (positions agents) (fst $ getGrid agents) --getGrid returns a tuple, but currently assume to be a square

baseline :: [Interaction] -> Float
baseline int = (fromIntegral total)/len
  where total = sum sums
        sums = map snd (showSums int)
        agents = nub  $ map (\(Interaction a1 a2 _ ) ->  a2) int
        len  = fromIntegral $ length agents

reproduce :: Float -> [Interaction] -> [Agent]  --so baseline isn't recalulated every time
reproduce _ [] = []
reproduce base interaction = winners ++ [newAgent] ++ reproduce base (tail interaction)
    where agents = nub $ concat $ map (\(Interaction a1 a2 _ ) -> a1:a2:[]) interaction
          winners = [a | a <- agents, (sumAgent interaction a) >= (round base)]
          newAgent = makeAgent (head winners) winners


main = do
    output "Length" (fromIntegral $ length int)
    output "Baseline" base
    output "Agents" agents
    output "Sums" (showSums int)
    output "winners" winners
    output "NeAgent" (makeAgent (head winners)winners)
    output "New Agents" (reproduce base int)

    where agents = generate 4
          int = playRound agents 20
          base = baseline int
          winners = [a | a <- agents, (sumAgent int a) >= (round base)]

这个主要功能应该重现的是根据父母的“适应性”是否超过一定水平来生成新的代理,然后在代理列表中除了该代理之外的所有代理运行相同的功能。

输出:

Length: 16
Baseline: 280.0
Agents: [c_pavlov(-1,-1),c_titForTat(-1,0),c_sucker(-1,1),b_grim(0,-1)]
Sums: [("c_pavlov",280),("c_titForTat",280),("c_sucker",280),("b_grim",280)]
winners: [c_pavlov(-1,-1),c_titForTat(-1,0),c_sucker(-1,1),b_grim(0,-1)]
NeAgent: c_pavlov1(0,0)
prisoners: Prelude.head: empty list

当我调用reproduce时,它会抛出prelude.head空列表错误,并且获胜者,代理和int列表都是非空的,因此在递归的最后一次迭代中可能是边缘大小写错误。为什么会这样?

2 个答案:

答案 0 :(得分:8)

解决方案相对简单:只需在Haskell程序中不使用 headtail。 (虽然有一些情况下这样做是合理的,但最好在开始时假设没有。)

相反,使用模式匹配。通常,您总是希望在空列表和非空列表上正确地匹配模式,如下所示:

fun :: [Something] -> ...
fun []       = ...
fun (x : xs) = ... -- x is head, xs is tail

这样,你就不得不处理错误,你知道引用xxs不能再失败,因为列表已经确定非空。

如果您的程序中有许多列表永远不会为空,那么您必须手动跟踪这些条件(并且至少应该记录它们)。但即使这样,最好在let中模式匹配 - 像这样绑定

(winner : _) = ...

然后将winner作为该列表的头部引用,因为您将收到一条错误消息,其中涉及模式匹配失败的行号。

答案 1 :(得分:1)

您没有确切地说出错误发生的位置。大概是你在没有检查列表是否为空的情况下调用 tail head时。

如果是这种情况,您可以使用空interaction列表的模式匹配来修复它。

否则,您需要提供有关错误的更多信息。

(编辑:用头替换尾巴)