繁体   English   中英

Haskell 程序错误:模式匹配失败

[英]Haskell Program error: pattern match failure

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 [] _ =[]

我制作了 Haskell Function,它将 3 个单词的出现频率除以前 2 个单词的出现频率。 例如,这是一个测试用例:

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

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

您的 function 匹配的两种模式是

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

function 的第一个定义假定第二个列表将匹配模式

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

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

genProbPairs _ [] = ...

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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