How to check the second argument between an operation of true and false in haskell? E.g, False && True will only check the first argument and then will stop the operation. Is there something like False & True in Haskell to check both arguments?
&& in the prelude is implemented as
(&&) :: Bool -> Bool -> Bool
True && x = x
False && _ = False
Which means in the case that the first argument is False the second
one is never evaluated. You could always implement your own version to have the behaviour that you want e.g.:
(.&&.) :: Bool -> Bool -> Bool
True .&&. x = x
False .&&. False = False
False .&&. True = False
In which the second second argument is evaluated in either case.
There is no good reason why you'd want this, but if you insist...
import Control.Parallel (pseq)
(&&!) :: Bool -> Bool -> Bool
a &&! b = b `pseq` (a&&b)
Usually, seq (which doesn't require any imports) will also suffice instead of pseq, but only the latter actually guarantees that b will be evaluated.
Of course, the semantics of this function will be exactly the same as && alone, it will just be slower in some cases.
I was mislead by the OP's subject "Operator & in haskell?"
For those who are here looking for (&) in Haskell
& is a reverse application operator in Data.Function
(&) :: a -> (a -> b) -> b
Related
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
Is it possible to write a contract that checks whether a statement is true?
For example, I want to define a contract
true :: Contract a
such that for all values x, the equation
assert true x == x
holds.
I have tried something like this:
true :: Contract a
true = Pred (\a -> True)
But when running assert true x == x compiler says that x is undefined.
When running assert true 5==6 the result is False, and I have hoped for a Contract violation error.
How should I change this true contract? Would appreciate your help.
Here
data Contract :: * -> * where
Pred :: (a -> Bool) -> Contract a
Fun :: Contract a -> Contract b -> Contract (a -> b)
Assert will cause a run-time failure if a contract is violated, and otherwise return the original result:
assert :: Contract a -> a -> a
assert (Pred p) x = if p x then x else error "contract violation"
assert (Fun pre post) f = assert post . f . assert pre
You can see the problem very clearly if you consider your definitions of true and assert. Here are the relevant parts:
true :: Contract a
true = Pred (\a -> True)
assert :: Contract a -> a -> a
assert (Pred p) x = if p x then x else error "contract violation"
...
Put them together and you see that assert true x will test (\a -> True) x and either produce x or throw an error, depending on if it's True or False. And that this will always be True, no matter what expression you use for x, since the predicate by definition always returns True, and ignores its argument.
The simple fix is to have the true "contract" actually test its argument, like this:
true :: Contract Bool
true = Pred id
That is, this new true can only apply to a value of type Bool (because it really doesn't make sense for any others) and does nothing to it. It lets the value through unchanged if it's True, and otherwise throws the contract violation error you want:
Prelude> assert true (5==6)
*** Exception: contract violation
CallStack (from HasCallStack):
error, called at <interactive>:21:46 in interactive:Ghci2
Prelude> assert true (5==5)
True
And note the parentheses in assert true (5==6), since assert true 5==6 is parsed as (assert true 5)==6, due to function application being the most precedent "operator" in Haskell. assert true 5==6 leads to an error because this corrected version of true only works on a Boolean value, and therefore not on 5.
Note that assert true x == x compares assert true x to x; so assert true 5 is 5 and of course 5 == 6 is false and not a contract violation.
If you intended assert true (x == x) to hold instead, then it seems like
true :: Contract Bool
true = Pred id
assert true (5==6) -- Contract violation
is what you want
"when running assert true x == x compiler says that x is undefined" is rather key here. Your assert call appears to me to be one expression containing two references to x, and the outermost function is (==). Neither side can be evaluated without a binding for x. The assert true x portion never sees ==, and if we rewrote it to assert true (x == x) we'd still need to provide an x :: Eq a. I don't know how to examine a function as such, but there certainly are options I'm not well versed in.
Why does this function always succeed? It always returns True with any values and any types. Is this the correct behavior?
f a b = case a of b -> True; _ -> False
The b in the case definition is not the b in in the head of the f definition. You created a new locally scoped variable. Your code is thus equivalent to:
f a b = case a of
c -> True
_ -> False
Pattern matching with a variable indeed always succeeds.
If you want to check if two values are the same, you will need to define some function (or let Haskell automatically derive Eq for example).
Note: you can turn on the -Wname-shadowing warning to let the compiler warn you about creating identifiers that shadow existing ones. For example your code will produce:
Prelude> f a b = case a of b -> True; _ -> False
<interactive>:1:19: warning: [-Wname-shadowing]
This binding for ‘b’ shadows the existing binding
bound at <interactive>:1:5
Just in addition to the perfect answer accepted, my two cents:
this:
f a b = case a of b -> True; _ -> False -- (A)
and this:
f a b = case a of
c -> True
_ -> False --(B)
are is equivalent to:
f a b = case a of
_ -> True
or
f a b = True
or
f _ b = True
So, be careful because that's the real behavior you created, a function that takes two parameters and returns always True.
Also:
(A) and (B) will show this warning if -Woverlapping-patterns is used:
warning: [-Woverlapping-patterns]
Pattern match is redundant
In a case alternative: _ -> ...
|
3 | _ -> False
| ^^^^^^^^^^
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
Been trying to write my own Prelude, and to write QuickCheck properties along with it. Writing Prelude is going well, but in doing the QuickCheck I have managed to get blocked early. Here are snippets of the 2 files I have:
-- MyLude.hs
module MyLude where
import Prelude (Bool(..))
(&&) :: Bool -> Bool -> Bool
(&&) True a = a
(&&) _ _ = False
-- MyLudeTest.hs
module MyLudeTest where
import qualified MyLude as P
prop_test_and a b = a && b == a P.&& b
Then in ghci I run:
:load MyLudeTest.hs
:m +Test.QuickCheck
quickCheck prop_test_and
and get the following error:
*** Failed! Falsifiable (after 1 test):
False
False
What confuses me is that I have implemented (||) and implemented a quickcheck property for it that does pretty much the same thing the prop_test_and does, and that seems to have no problems. What am I missing?
This is just operator precedence at work. Your property is parsed as:
prop_test_and a b = a && (b == a) P.&& b
Precedence!
Prelude Test.QuickCheck> (False && False) == myand False False
True
Prelude Test.QuickCheck> False && False == myand False False
False
You're missing parens around your operators. Remember (&&) binds weaker (3) than (==) (4)