Haskell own instance typeclass - class

I need to declare my own typeclass but I dont understand why there is the (==).
data Egg = Soft | Hard
instance Eq Egg where
(==)
I did not find anything where the (==) is used in an instance, only in a class

The easy way to have an instance of Eq is:
data Egg = Soft | Hard deriving Eq
The hard way (with more control):
data Egg = Soft | Hard
instance Eq Egg where
Soft == Soft = True
Hard == Hard = True
_ == _ = False
UPD: Since the equality function (==) as an operator seem to be the confusing bit, here is the same instance written with a prefix notation:
data Egg = Soft | Hard
instance Eq Egg where
(==) Soft Soft = True
(==) Hard Hard = True
(==) _ _ = False
As a quick reminder: operator are infix (in between terms) by default, and functions are prefix (before terms) by default. To make an operator prefix it is surrounded by (), to make a function infix it is surrounded by ``. Here is a thread talking about which characters are used for operator vs functions.

I assume you’re trying to make an instance of the standard typeclass Eq for your custom datatype. The Eq class is defined as:
class Eq a where
(==) :: a -> a -> Bool
a == b = not (a /= b)
(/=) :: a -> a -> Bool
a /= b = not (a == b)
That is, it defines two methods == and /= (which happen to be operators), and provides default implementations of each one in terms of the other. So to make an instance of Eq for your own type, you need to provide an implementation of one or both of these functions (== or /=) for your type. Note that the body of the instance must be indented.
instance Eq Egg where
Soft == Soft = True
Hard == Hard = True
_ == _ = False
Just as you can use a Haskell operator in prefix form by wrapping it in parentheses, e.g., (==) 1 1, you can also implement an operator definition in prefix form:
instance Eq Egg where
(==) Soft Soft = True
(==) Hard Hard = True
(==) _ _ = False
You could even use a case if you so desired:
instance Eq Egg where
(==) a b = case (a, b) of
(Soft, Soft) -> True
(Hard, Hard) -> True
_ -> False
Note that these are all the same as the instance that would be generated for you automatically with deriving:
data Egg = Soft | Hard
deriving (Eq)

Related

Forcing evaluation of terms before extraction, or other ways to test extracted functions?

In many parts of the standard library, there are a bunch of OCaml-native functions with no Coq counterpart. I implemented a Coq version of some of them (with added proofs to show that the Coq versions behave as I think they ought to), but now how do I check that this actually matches the OCaml version's behavior?
The easiest / most "obvious" way I can think of would be to take a test input x, compute f x in Coq, and extract a comparison f x = [[f x]] (where [[…]] marks evaluation in Coq), then repeat for some number of test cases. Unfortunately, I can't find a way to force evaluation in Coq.
Is there a trick to make this possible? Or is there some other standard way for testing behavior across extraction? (Manually going Compute (f x). and plugging the resulting terms as literals back into the sanity checks would be an ugly fallback… Unfortunately, those won't update automatically when the function is changed, and it would also be a lot of manual work that doesn't exactly encourage exhaustive tests…)
Minimal sample:
Definition foo (b : bool) : bool :=
match b with | true => false | false => true end.
Extract Inlined Constant foo => "not".
Extract Inlined Constant bool_eq => "(=)".
Definition foo_true := foo true.
Definition foo_false := foo false.
Definition foo_test : bool :=
andb (bool_eq (foo true) foo_true) (bool_eq (foo false) foo_false).
Recursive Extraction foo_test.
results in
(** val foo_true : bool **)
let foo_true = not true
(** val foo_false : bool **)
let foo_false = not false
(** val foo_test : bool **)
let foo_test = (&&) ((=) (not true) foo_true) ((=) (not false) foo_false)
which is unhelpful. All the ways I could think of to change the definition of foo_true/foo_false to try and have them pre-evaluated didn't work. I can't find any flag in the extraction mechanism to force evaluation… Both the reference manual's attribute index and the flags/options/tables index didn't contain anything that looks useful. Is there anything that I missed?
Starting a definition with Eval compute in evaluates it before registering the definition.
Definition foo_true := Eval compute in foo true.
Definition foo_false := Eval compute in foo false.
Definition foo_test : bool :=
andb (bool_eq (foo true) foo_true) (bool_eq (foo false) foo_false).
Recursive Extraction foo_test.

Combining two switch cases in reasonML

| (true, Select(true)) => true
| (false, Select(false)) => false
How can I combine these two in a switch statement with generic type?
Unfortunately the patterns that you match against in a switch statement have to be 'linear' (ie, the variants inside the patterns should only appear once):
See https://caml.inria.fr/pub/docs/oreilly-book/html/book-ora016.html
A pattern must necessarily be linear, that is, no given variable can occur more than once inside the pattern being matched. Thus, we might have hoped to be able to write:
# let equal c = match c with
(x,x) -> true
| (x,y) -> false;; Characters 35-36: This variable is bound several times in this matching
But this would have required the compiler to know how to carry out
equality tests. Yet this immediately raises numerous problems. If we
accept physical equality between values, we get a system which is too
weak, incapable of recognizing the equality between two occurrences of
the list [1; 2], for example. If we decide to use structural equality,
we run the risk of having to traverse, ad infinitum, circular
structures.
Note that ReasonML is just an alternative syntax for OCaml, so the above also holds for Reason. match is just the OCaml version of switch.
It is possible to combine the two cases generically using a when guard:
let f = (a, b) =>
switch (a, b) {
| (a, Select(b)) when a == b => a
};
However, note that this isn't exhaustive, and you haven't specified what should be returned in the case that a != b. To avoid the non-exhaustiveness warning, and crash at runtime, you need to add another case to cover that.
Yeah this is doable:
// using switch
let theSolution = x => switch(x) {
| (_, Select(inside)) => inside
};
// using `fun`
let theSolution = x => x |> fun | (_, Select(inside)) => inside;
// or for a super short solution:
let theSolution = fun | (_, Select(inside)) => inside;
For example:
type select = | Select(bool);
let a = (true, Select(true));
let b = (true, Select(false));
let c = (false, Select(true));
let d = (false, Select(false));
let theSolution = x => x |> fun | (_, Select(inside)) => inside;
Js.log2("A is", theSolution(a));
Js.log2("B is", theSolution(b));
Js.log2("C is", theSolution(c));
Js.log2("D is", theSolution(d));
Will result in:
"A is" true
"B is" false
"C is" true
"D is" false
Or if you want to compare the booleans, you can do either of:
let theSolution = fun | (a, Select(b)) => a && b;
let theSolution = fun | (a, Select(b)) => a == b;
See this example in the online repl
Following can be a solution for your problem. The operation a&&b depends on what logic you want the block to follow. I took a reasonable assumption that you wanted to perform AND operation. If you provide other possible conditions then this can be refined.
let getSelectionResponse = x => switch(x){ | (a, Select(b)) => a&&b};
Tried it here

Implementing an interface for a plain old recursive data type

I'm fighting with Idris syntax, it seems.
module Test
data Nat = Z | S Nat
Eq Nat where
Z == Z = True
S n1 == S n2 = n1 == n2
_ == _ = False
This complains with the following error (v1.1.1):
.\.\Test.idr:5:8: error: expected: "#",
"with", argument expression,
constraint argument,
function right hand side,
implicit function argument,
with pattern
Eq Nat where
^
Type checking .\.\Test.idr
I don't understand why, I basically used the same syntax as the docs.
When I write an Eq implementation for a custom, non-recursive type, such as Bool, it compiles just fine.
You need to wrap S n patterns in parenthesis. After doing that, your will get compiler errors because Nat is already defined in Prelude. So to compile your code just replace Nat with Natural (or anything else). Though, Z and S constructors are also defined in Prelude so you either need to rename everything to be able to test in REPL easily or use %hide directive.
But at least this code compiles:
module Test
data Natural = Z | S Natural
Eq Natural where
Z == Z = True
(S n1) == (S n2) = n1 == n2
_ == _ = False

Scala's || and | operators

I noticed something today. Scala has the usual OR ||, but also the |.
My first thought was that the | was a strict OR. So true | true, will evaluate to false.
But,
val x = true
x: Boolean = true
val y = true
y: Boolean = true
x || y
res4: Boolean = true
x | y
res5: Boolean = true
What is the | operator for? Is it just an alias?
As in Java, the single & and | operators do the same thing as their usual versions but without short-circuiting.
As an example, consider the expression true || isNice(). The method will never be called because true || x is always true and the compiler (and runtime) knows that. If you insist on all parts of a boolean expression to be evaluated, you have to use & or |.
Edit: For completeness, Scala also uses the | for alternative patterns in pattern matching. This is copied from the language reference:
8.1.11 Pattern Alternatives
Syntax:
Pattern ::= Pattern1 { ‘|’ Pattern1 }
A pattern alternative p1 | ... | pn consists of a number of alternative patterns
pi
. All alternative patterns are type checked with the expected type of the pattern.
They may no bind variables other than wildcards. The alternative pattern matches
a value v if at least one its alternatives matches v.

&& and || in Scala

since normal operators like +, ::, -> and so on are all methods which can be overloaded and stuff I was wondering if || and && are methods as well. This could theoretically work if this were methods in of the boolean object.
But if they are, why is something like
if (foo == bar && buz == fol)
possible? If the compiler reads from right to left this would invoke && on bar instead of (foo == bar)
6.12.3 Infix Operations An infix operator can be an arbitrary
identifier. Infix operators have
precedence and associativity defined
as follows:
The precedence of an infix
operator is determined by the
operator’s first character. Characters
are listed below in increasing order
of precedence, with characters on the
same line having the same precedence.
(all letters)
|
^
&
< >
= !
:
+ -
* / %
(all other special characters)
That is, operators starting with a
letter have lowest precedence,
followed by operators starting with
‘|’, etc.
There’s one exception to
this rule, which concerns assignment
operators(§6.12.4). The precedence of
an assigment operator is the same as
the one of simple assignment (=). That
is, it is lower than the precedence of
any other operator.
It follows with an explanation of associativity, and how it all combines in a expression with multiple operators. The Scala Reference makes good reading.
Because method starts with = has a higher precedence than method starts with &.
So (foo == bar && buz == fol) will become something like the following:
val tmp1: Boolean = (foo == bar)
val tmp2: Boolean = (buz == fol)
tmp1 && tmp2
Those two are definitely methods in scala.