[英]Haskell Pattern Matching Booleans
I need help to fix this Haskell function using pattern matching.我需要帮助来使用模式匹配修复此 Haskell function。 It should only return true if every formula in the list of formulas is True.
只有当公式列表中的每个公式都为 True 时,它才应该返回 True。 Here is what I have so far:
这是我到目前为止所拥有的:
eval_list :: [Formula] -> Bool
eval_list (f:fx) = (eval_list f) && (eval_list fx)
here is how Formula is defined:以下是公式的定义方式:
data Formula = And Formula Formula
| Not Formula
| Con Bool
deriving Show
You forgot to implement the case for an empty list.您忘记为空列表实施案例。 Since you each time recurse with a list item that is one item shorter than the previous call, eventually you will make a recursive call with an empty list.
由于您每次都使用比上一次调用短一个项目的列表项进行递归,因此最终您将使用空列表进行递归调用。
Another problem is that you call eval_list f
, but f
is the first item of your list and thus a Formula
object, not a list of Formula
s.另一个问题是您调用
eval_list f
,但f
是列表的第一项,因此是Formula
object,而不是Formula
的列表。 You likely should use a eval_formula
to evaluate the formula.您可能应该使用
eval_formula
来计算公式。
You thus can implement this with:因此,您可以通过以下方式实现:
eval_list :: [Formula] -> Bool
eval_list [] = True
eval_list (f:fx) = eval_formula f && eval_list fx
where you will have to implement eval_formula
yourself.您必须自己实施
eval_formula
的地方。
You do not need to use explicit recursion.您不需要使用显式递归。 You can for example work with
all:: Foldable f => (a -> Bool) -> fa -> Bool
:例如,您可以使用
all:: Foldable f => (a -> Bool) -> fa -> Bool
:
eval_list :: Foldable f => f Formula -> Bool
eval_list = all eval_formula
In order to evaluate a single Formula
, you can use recursion, the function thus will look like:为了评估单个
Formula
,您可以使用递归,因此 function 将如下所示:
eval_formula :: Formula -> Bool
eval_formula (And f1 f2) = …
eval_formula (Not f) = …
eval_formula (Con b) = …
where I leave implement the …
parts as an exercise.我离开的地方将
…
部分作为练习。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.