Haskell程序返回空列表

问题描述 投票:-2回答:1
genProbPairs (((a,b,c),d):xs) (((e,f),g):ys) =
  if a==e && b==f
  then [((a,b,c),d/g)]++genProbPairs xs (((e,f),g):ys)
  else genProbPairs (((a,b,c),d):xs) ys

genProbPairs [] _ =[]
genProbPairs _ []=[]

我制作了Haskell函数,该函数将3个单词出现的频率与前2个单词出现的频率相除。例如,这是一个测试给定Trigram频率列表,它用于为每个Trigram生成概率列表。Bigram频率的另一个列表

情况:

genProbPairs
  [ (("the","man","is"),1)
  , (("man","is","the"),1)
  , (("is","the","man"),1)
  , (("the","man","."),1)
  , (("man",".","the"),1)
  , ((".","the","man"),1)
  , (("the","man","saw"),1)]
  [ (("man","is"),1)
  , (("is","the"),1)
  , (("man","."),1)
  , ((".","the"),1)
  , (("the","man"),3)
  , (("man","saw"),1)]

预期的答案是:

[ (("the","man","is"),0.333333333333333)
, (("man","is","the"),1.0)
, (("is","the","man"),1.0)
, (("the","man","."),0.333333333333333)
, (("man",".","the"),1.0)
, ((".","the","man"),1.0)
, (("the","man","saw"),0.333333333333333)
]

我在运行时遇到问题,它没有分开并且以下消息发生错误:

Program error: pattern match failure: genProbPairs [(("the","man","is"),1),(("man","is","the"),1),(("is","the","man"),1),(("the","man","."),1),(("man",".","the"),1),((".","the","man"),1),(("the","man","\rsaw"),1)] []

问题出在哪里,我该如何解决?

haskell
1个回答
1
投票

您的函数匹配的两个模式是

genProbPairs (((a,b,c),d):xs) (((e,f),g):ys) = ...
genProbPairs [] _ = ...

该函数的第一个定义假定第二个列表将与模式匹配

(((e,f),g):ys)

在此模式中使用:意味着该模式将与包含至少一个元素的列表匹配。如果列表为空,则此模式将不匹配。但是,如果第二个列表为空,而第一个列表为not空,则该函数的定义均不可用,并且您的程序将崩溃!为了解决这个问题,您需要添加另一个定义-一个看起来像

genProbPairs _ [] = ...

...确切要替换的是您需要根据问题的需求弄清楚的东西。

© www.soinside.com 2019 - 2024. All rights reserved.