Home > Mobile >  Haskell Pattern Matching Booleans
Haskell Pattern Matching Booleans

Time:10-06

I need help to fix this Haskell function using pattern matching. It should only return true if every formula in the list of formulas is 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

CodePudding user response:

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 Formulas. You likely should use a eval_formula to evaluate the 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.

You do not need to use explicit recursion. You can for example work with all :: Foldable f => (a -> Bool) -> f a -> 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:

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.

  • Related