【发布时间】:2014-09-16 14:03:21
【问题描述】:
我正在尝试获取 Haskell 列表中的第二项。我认为最好的方法是获取列表尾部的头部。
secondMostRecentChoice :: History -> Choice // a choice is just a Bool like Bake | NoBake
secondMostRecentChoice [] = "Not Enough History"
secondMostRecentChoice history =
if ( length history == 1 )
then "Still Not Enough History"
else if (length history >= 2)
then (head [b | (head a,b) <- history]) //Here is the problem
else "Not supposed to be here"
else "Not supposed to be here"
但我得到以下信息:
模式中的解析错误:head
可能是因为缺少“做”?
为什么我需要do 或者这是一个错误的建议?
【问题讨论】:
-
是的,这是一个错误的建议。你可以写你想要的,因为
head [b | (a:b:_) <- history]—a已经是一个“头”了。但是,如果可以避免的话,您应该永远测量列表中的length。正如一些答案所建议的那样,在这里您可以通过将函数本身定义为模式匹配(a.o.t. 在列表理解中使用模式匹配)来避免它。
标签: haskell