Are there any tools for guard analysis? - haskell

I'm a Haskell noob and while reading about Implications in Haskell Road I came to following puzzle.
verdict :: Bool -> Bool -> (Bool, String)
verdict p q | not result = (False, "LIAR")
| result && p = (True, "telling the truth")
| result = (True, "innocent unless proven guilty")
| otherwise = (False, "we shouldn't get here")
where result = (not p) || q
-- map (\x -> verdict (fst x == 1) (snd x == 1)) [(1,1),(1,0),(0,1),(0,0)]
Is there a tool that would warn me about the otherwise or other similar logical errors?

I think I would write this function a different way:
-- not result
verdict True False = (False, "LIAR")
-- result && p
verdict True True = (True , "telling the truth")
-- result
verdict False _ = (True , "innocent unless proven guilty")
verdict _ True = (True , "innocent unless proven guilty")
-- otherwise
verdict _ _ = (False, "we shouldn't get here")
Then not only is it obvious to humans which clauses can be left out (the last two), but also to the machine; ghc says this at its default warning level:
test.hs:2:5: Warning:
Pattern match(es) are overlapped
In an equation for ‘verdict’:
verdict _ True = ...
verdict _ _ = ...
Checking guard overlap in general is of course undecidable; and furthermore I don't know of a tool that will try to give an approximate answer.

This is probably a clearer expression of your intent:
implies :: Bool -> Bool -> Bool
p `implies` q = not p || q -- The backticks allow infix usage.
-- The assumption is that p `implies` q is a known fact.
verdict :: Bool -> Bool -> (Bool, String)
verdict p q = (result, remark)
where
result = p `implies` q
remark
| not result = "LIAR"
| p = "telling the truth"
| otherwise = "innocent until proven guilty"
Guards are syntax sugar for pattern matches on Bool values. For general tips on arranging pattern matches, see Daniel Wagner's answer.

Related

What does this statement mean in Haskell?

I'm currently still getting to know more about Haskell, under the topic of Pattern Matching, what does it mean by _ && _ = False in Haskell? I came across this statement in one of the lecture slides, like what does it mean by the underscores? Thanks again!
The underscores are wildcards. That is, they match any value, but do not bind the value to a name. A common example of this usage is:
True && True = True
_ && _ = False
Underscores means a wildcard. It binds with any value. It thus means that for any value for the left and right operand for the given type of the function, it will fire that clause, and thus return False.
One can thus define (&&) :: Bool -> Bool -> Bool with:
(&&) :: Bool -> Bool -> Bool
True && True = True
_ && _ = False
The real implementation of (&&) is however lazy in its second parameter, and is implemented as [src]:
-- | Boolean \"and\"
(&&) :: Bool -> Bool -> Bool
True && x = x
False && _ = False

How do you create quickCheck properties with a Property output in Haskell?

How do you create a property that checks that all solutions provided are valid solutions, I need it to output as a Property, but I'm unsure how to do that, I only understand how to do Bool outputs for quickCheck properties. See below for my attempt, and the general idea of how I want it to function:
solve :: Sudoku -> Maybe Sudoku
solve s = solve' (blanks s) s
solve' :: [Pos] -> Sudoku -> Maybe Sudoku
solve' blankl s
| not (isOkay s) = Nothing
| isFilled s = Just s
| otherwise = listToMaybe [fromJust sol | n <- [1..9],
let sol = solve' (tail blankl) (update s (head blankl) (Just n)),
sol /= Nothing]
isSolutionOf :: Sudoku -> Sudoku -> Bool
isSolutionOf s1 s2 =
isOkay s1
&& isFilled s1
&& and [ a == b || b == Nothing |
(a,b) <- zip (concat (rows s1)) (concat (rows s2)) ]
prop_SolveSound :: Sudoku -> Property
prop_SolveSound s
| solution == Nothing = True
| otherwise = isSolutionOf (fromJust solution) s where
solution = solve s
Any help is much appreciated, I guess what I'm asking is how can you convert the - quite clearly - Bool output from prop_SolveSound to a Property output?
At the very simplest, you can use property method to convert e.g. Bool to Property. I suggest to look at the instances of Testable class, and try to understand what each of them does, and how it can be used.
Or you can be more sophisticated and use some other functions returning Property, e.g. ===. That might be tricky in your example.
One quite useful function, is counterexample. It allows you to print additional output, when property doesn't hold. For example, it's used to implement ===:
(===) :: (Eq a, Show a) => a -> a -> Property
x === y =
counterexample (show x ++ interpret res ++ show y) res
where
res = x == y
interpret True = " == "
interpret False = " /= "
As this is an assignment, I'm not giving you any more hints.

Wild card matching pattern in Haskell

OCaml provides wild card matching pattern when every other case fails:
let imply v = match v with
(true,false) -> false
| _ -> true;;
What's the equivalence in Haskell?
Better separate the function definition, like this
imply :: (Bool, Bool) -> Bool
imply (True, False) = False
imply _ = True
Now, whenever the pattern (True, False) is passed to imply, it will return False, on all other cases it will return True.
Also, what you have actually done is perfectly fine, if you are defining it in interactive shell, better watch out for the indentation errors.
Prelude> :{
Prelude| let imply v = case v of
Prelude| (True, False) -> False
Prelude| _ -> True
Prelude| :}
Prelude> imply (False, True)
True
Prelude> imply (True, False)
False
Prelude> imply (True, True)
True
Prelude> imply (False, False)
True

In Haskell, are guards or matchers preferable?

I'm learning Haskell, and it's not always clear to me when to use a matcher and when to use a guard. For certain scenarios it seems that matchers and guards can be used to achieve essentially the same ends. Are there some rules or heuristics for when it's better to use matches over guards or vice versa? Is one more performant than the other?
To illustrate what I'm getting at, here are a couple of silly examples I cooked up that seem to be equivalent, but one version uses matchers and the other uses guards:
listcheck :: [a] -> String
listcheck [] = "List is null :-("
listcheck a = "List is NOT null!!"
listcheck' a
| null a = "List is null :-("
| otherwise = "List is NOT null!!"
and
luckyseven :: Int -> String
luckyseven 7 = "SO LUCKY!"
luckyseven b = "Not so lucky :-/"
luckyseven' c
| c == 7 = "SO LUCKY!"
luckyseven' c = "Not so lucky :-/"
Thanks!
These can often be used interchangeably, but there are significant differences between the two. Pattern matching can only occur on constructors, so computations can not be performed inside of a pattern, while guards are simply multi-branch if-else statements. For example, I can't write a pattern equivalent of the following:
func :: Int -> Int
func x
| even x = 3 * x
| odd x = 7 * x -- alternatively "otherwise = 7 * x" to get rid of all those pesky compiler warnings
This just wouldn't be possible with just pattern matching. You also can't do things like
func :: Int -> Maybe String
func x
| x < 0 = Nothing
| x == 0 = Just "Zero"
| x < 20 = Just "Small"
| x < 100 = Just "Big"
| x < 1000 = Just "Huge"
| otherwise = Just "How did you count that high?"
Conversely, guards using ADTs don't give you much information without helper functions. If I had the type
data Expr
= Literal Int
| Add Expr Expr
| Mult Expr Expr
| Negate Expr
deriving (Eq, Show)
Using guards to write the equivalent of
eval :: Expr -> Int
eval (Literal i) = i
eval (Add e1 e2) = eval e1 + eval e2
eval (Mult e1 e2) = eval e1 * eval e2
eval (Negate e) = negate (eval e)
would be a lot more verbose, difficult, and annoying. In fact, at some level you'd have to resort to pattern matching to do things like
getLiteral :: Expr -> Int
getLiteral (Literal i) = i
getLiteral _ = error "Not a literal"
Which introduces functions that can error, which is bad. In this case, using pattern matching is much preferred over using guards.
For your particular examples, I'd go with pattern matching, but would use _ where possible:
listCheck :: [a] -> String
listCheck [] = "List is null :-("
listCheck _ = "List is NOT null!!"
and
luckySeven :: Int -> String
luckySeven 7 = "SO LUCKY!"
luckySeven _ = "Not so lucky :-/"
That emphasizes that if the list isn't empty, or the Int isn't 7, nothing else matters, and you aren't going to use its particular value to produce the function result. bheklilr has capably pointed out places where one choice or the other is definitely preferable.

Defining a Boolean function on Haskell that determines if an element occurs once in a list

So I'm trying to define a function in Haskell that if given an integer and a list of integers will give a 'true' or 'false' whether the integer occurs only once or not.
So far I've got:
let once :: Eq a => a -> [a] -> Bool; once x l =
But I haven't finished writing the code yet. I'm very new to Haskell as you may be able to tell.
Start off by using pattern matching:
once x [] =
once x (y:ys) =
This won't give you a good program immediately, but it will lead you in the right direction.
Here's a solution that doesn't use pattern matching explicitly. Instead, it keeps track of a Bool which represents if a occurance has already been found.
As others have pointed out, this is probably a homework problem, so I've intentionally left the then and else branches blank. I encourage user3482534 to experiment with this code and fill them in themselves.
once :: Eq a => a -> [a] -> Bool
once a = foldr f False
where f x b = if x == a then ??? else ???
Edit: The naive implementation I was originally thinking of was:
once :: Eq a => a -> [a] -> Bool
once a = foldr f False
where f x b = if x == a then b /= True else b
but this is incorrect as,
λ. once 'x' "xxx"
True
which should, of course, be False as 'x' occurs more than exactly once.
However, to show that it is possible to write once using a fold, here's a revised version that uses a custom monoid to keep track of how many times the element has occured:
import Data.List
import Data.Foldable
import Data.Monoid
data Occur = Zero | Once | Many
deriving Eq
instance Monoid Occur where
mempty = Zero
Zero `mappend` x = x
x `mappend` Zero = x
_ `mappend` _ = Many
once :: Eq a => a -> [a] -> Bool
once a = (==) Once . foldMap f
where f x = if x == a then Once else Zero
main = do
let xss = inits "xxxxx"
print $ map (once 'x') xss
which prints
[False,True,False,False,False]
as expected.
The structure of once is similar, but not identical, to the original.
I'll answer this as if it were a homework question since it looks like one.
Read about pattern matching in function declarations, especially when they give an example of processing a list. You'll use tools from Data.List later, but probably your professor is teaching about pattern matching.
Think about a function that maps values to a 1 or 0 depending on whethere there is a match ...
match :: a -> [a] -> [Int]
match x xs = map -- fill in the thing here such that
-- match 3 [1,2,3,4,5] == [0,0,1,0,0]
Note that there is the sum function that takes a list of numbers and returns the sum of the numbers in the list. So to count the matches a function can take the match function and return the counts.
countN :: a -> [a] -> Int
countN x xs = ? $ match x xs
And finally a function that exploits the countN function to check for a count of only 1. (==1).
Hope you can figure out the rest ...
You can filter the list and then check the length of the resulting list. If length == 1, you have only one occurrence of the given Integer:
once :: Eq a => a -> [a] -> Bool
once x = (== 1) . length . filter (== x)
For counting generally, with import Data.List (foldl'), pointfree
count pred = foldl' (\ n x -> if pred x then n + 1 else n) 0
applicable like
count (< 10) [1 .. 10] == 9
count (== 'l') "Hello" == 2
gives
once pred xs = count pred xs == 1
Efficient O(n) short-circuit predicated form, testing whether the predicate is satisfied exactly once:
once :: (a -> Bool) -> [a] -> Bool
once pred list = one list 0
where
one [] 1 = True
one [] _ = False
one _ 2 = False
one (x : xs) n | pred x = one xs (n + 1)
| otherwise = one xs n
Or, using any:
none pred = not . any pred
once :: (a -> Bool) -> [a] -> Bool
once _ [] = False
once pred (x : xs) | pred x = none pred xs
| otherwise = one pred xs
gives
elemOnce y = once (== y)
which
elemOnce 47 [1,1,2] == False
elemOnce 2 [1,1,2] == True
elemOnce 81 [81,81,2] == False

Resources