Ord: No type class instance was found for Data.Eq.Eq (Extended a0). PureScript by Example book, Chapter 6 - typeclass

I am quite new to Haskell/Purescript and currently learning by studying the PureScript by Example book.
In chapter 6 about type classes, exercise 4 has following task:
(Medium) Given any type a with an instance of Ord, we can add a new "infinite" value which is greater than any other value:
data Extended a = Finite a | Infinite
Write an Ord instance for Extended a which reuses the Ord instance for a.
Here is my attempt:
instance ordExtended :: Ord a => Ord (Extended a) where
compare Infinite Infinite = EQ
compare Infinite _ = GT
compare _ Infinite = LT
compare (Finite f1) (Finite f2) = compare f1 f2
Unfortunately, the code triggers an error:
No type class instance was found for
Data.Eq.Eq (Extended a0)
while checking that expression #dict Eq
has type { eq :: Extended a0 -> Extended a0 -> Boolean
}
in value declaration ordExtended
where a0 is a rigid type variable
bound at (line 0, column 0 - line 0, column 0)
PureScript(NoInstanceFound)
I cannot quite understand the error message:
What does expression #dict Eq mean? There is no dict in my code.
What is a rigid type variable?
The error seems to use different identifiers like a0 (why? I assume, that is a)
In my book, Eq type class instance should be covered by implementing Ord, as Ord extends Eq.

The key part of the error is at the start:
No type class instance was found for
Data.Eq.Eq (Extended a0)
Here is the definition of Ord:
class Eq a <= Ord a where
compare :: a -> a -> Ordering
This is actually the superclass syntax, saying that you need an Eq instance to have an Ord instance. So, you can fix the error by making an Eq instance:
instance eqExtended :: Eq a => Eq (Extended a) where
eq Infinite Infinite = true
eq (Finite f1) (Finite f2) = eq f1 f2
eq _ _ = false
instance ordExtended :: Ord a => Ord (Extended a) where
compare Infinite Infinite = EQ
compare Infinite _ = GT
compare _ Infinite = LT
compare (Finite f1) (Finite f2) = compare f1 f2
As to why a0 is used, it seems the purescript compiler just likes adding numbers after type variables, possibly to reduce vagueness or to allow for scoped type variables. You can read about rigid type variables here (they're basically variables that can't be changed to fit constraints).

Related

Is there a better way to write a commutative function in F#/OCaml?

Is there a more elegant or better way to write a commutative function in F#/OCaml rather than listing all possible cases?
let commutative x y =
match x,y with
a, _ -> val1
|_, a -> val1
|b, _ -> val2
|_, b -> val2
...
|_,z -> |valN
While I was writing the question I thought one could make the function recursive and swap the arguments if no match is found.
let rec commutative x y =
match x,y with
a,_ -> val1
|b,_ -> val2
...
|nox,noy -> commutative noy nox
But if I adopt this approach I cannot have in the function a default case that matches with everything unless I add another argument whose value indicates if it's the second time the function is being called and return the default value instead of calling the function with the swapped args if that's the case.
Any other ideas?
Does the language offer a construct for expressing the fact a function I'm defining is commutative?
(I'm answering for OCaml only as my F# is extremely rusty.)
There's no special help in OCaml for defining commutative functions.
If your parameter type has a reasonable ordering relation you can swap them if necessary to make x the larger (say). Almost all types can be compared in OCaml, so this should work very commonly. (Things that can't be compared: function types, cyclic values.)
I'm not sure this would help, but it might reduce the number of cases that you need to write out:
let commutative x y =
match (max x y, min x y) with
| A, _ -> value
. . .

How to properly create and use polynomial type and term type in f#

I'm trying to do this exercise:
I'm not sure how to use Type in F#, in F# interactive, I wrote type term = Term of float *int, Then I tried to create a value of type term by let x: term = (3.5,8);;But it gives an error.
Then I tried let x: term = Term (3.5,8);; and it worked. So Why is that?
For the first function, I tried:
let multiplyPolyByTerm (x:term, p:poly)=
match p with
|[]->[]
But that gives an error on the line |[]->[] saying that the expression is expecting a type poly, but poly is a in fact a list right? So why is it wrong here? I fixed it by |Poly[]->Poly[]. Then I tried to finish the function by giving the recursive definition of multiplying each term of the polynomial by the given term: |Poly a::af-> This gives an error so I'm stuck on trying to break down the Poly list.
If anyone has suggestion on good readings about Type in F#, please share it.
I got all the methods now, However,I find myself unable to throw an exception when the polynomial is an empty list as the base case of my recursive function is an empty list. Also, I don't know how to group common term together, Please help, Here are my codes:
type poly=Poly of (float*int) list
type term = Term of float *int
exception EmptyList
(*
let rec mergeCommonTerm(p:poly)=
let rec iterator ((a: float,b: int ), k: (float*int) list)=
match k with
|[]->(a,b)
|ki::kf-> if b= snd ki then (a+ fst ki,b)
match p with
|Poly [] -> Poly []
|Poly (a::af)-> match af with
|[]-> Poly [a]
|b::bf -> if snd a =snd b then Poly (fst a +fst b,snd a)::bf
else
*)
let rec multiplyPolyByTerm (x:term, p:poly)=
match x with
| Term (coe,deg) -> match p with
|Poly[] -> Poly []
|Poly (a::af) -> match multiplyPolyByTerm (x,Poly af) with
|Poly recusivep-> Poly ((fst a *coe,snd a + deg)::recusivep)
let rec addTermToPoly (x:term, p:poly)=
match x with
|Term (coe, deg)-> match p with
|Poly[] -> Poly [(coe,deg)]
|Poly (a::af)-> if snd a=deg then Poly ((fst a+coe,deg)::af)
else match addTermToPoly (x,Poly af) with
|Poly recusivep-> Poly (a::recusivep)
let rec addPolys (x:poly, y: poly)=
match x with
|Poly []->y
|Poly (xh::xt)-> addPolys(Poly xt,addTermToPoly(Term xh, y))
let rec multPolys (x:poly,y:poly)=
match x with
|Poly []-> Poly[]
|Poly (xh::xt)->addPolys (multiplyPolyByTerm(Term xh,y),multPolys(Poly xt,y))
let evalTerm (values:float) (termmm : term) :float=
match termmm with
|Term (coe,deg)->coe*(values**float(deg))
let rec evalPoly (polyn : poly, v: float) :float=
match polyn with
|Poly []->0.0
|Poly (ph::pt)-> (evalTerm v (Term ph)) + evalPoly (Poly pt,v)
let rec diffPoly (p:poly) :poly=
match p with
|Poly []->Poly []
|Poly (ah::at)-> match diffPoly (Poly at) with
|Poly [] -> if snd ah = 0 then Poly []
else Poly [(float(snd ah)*fst ah,snd ah - 1)]
|Poly (bh::bt)->Poly ((float(snd ah)*fst ah,snd ah - 1)::bh::bt)
As I mentioned in a comment, reading https://fsharpforfunandprofit.com/posts/discriminated-unions/ will be very helpful for you. But let me give you some quick help to get you unstuck and starting to solve your immediate problems. You're on the right track, you're just struggling a little with the syntax (and operator precedence, which is part of the syntax).
First, load the MSDN operator precedence documentation in another tab while you read the rest of this answer. You'll want to look at it later on, but first I'll explain a subtlety of how F# treats discriminated unions that you probably haven't understood yet.
When you define a discriminated union type like poly, the name Poly acts like a constructor for the type. In F#, constructors are functions. So when you write Poly (something), the F# parser interprets this as "take the value (something) and pass it to the function named Poly". Here, the function Poly isn't one you had to define explicitly; it was implicitly defined as part of your type definition. To really make this clear, consider this example:
type Example =
| Number of int
| Text of string
5 // This has type int
Number 5 // This has type Example
Number // This has type (int -> Example), i.e. a function
"foo" // This has type string
Text "foo" // This has type Example
Text // This has type (string -> Example), i.e. a function
Now look at the operator precedence list that you loaded in another tab. Lowest precedence is at the top of the table, and highest precedence is at the bottom; in other words, the lower something is on the table, the more "tightly" it binds. As you can see, function application (f x, calling f with parameter x) binds very tightly, more tightly than the :: operator. So when you write f a::b, that is not read as f (a::b), but rather as (f a)::b. In other words, f a::b reads as "Item b is a list of some type which we'll call T, and the function call f a produces an item of type T that should go in front of list b". If you instead meant "take the list formed by putting item a at the head of list b, and then call f with the resulting list", then that needs parentheses: you have to write f (a::b) to get that meaning.
So when you write Poly a::af, that's interpreted as (Poly a)::af, which means "Here is a list. The first item is a Poly a, which means that a is a (float * int) list. The rest of the list will be called af". And since the value your passing into it is not a list, but rather a poly type, that is a type mismatch. (Note that items of type poly contain lists, but they are not themselves lists). What you needed to write was Poly (a::af), which would have meant "Here is an item of type poly that contains a list. That list should be split into the head, a, and the rest, af."
I hope that helped rather than muddle the waters further. If you didn't understand any part of this, let me know and I'll try to make it clearer.
P.S. Another point of syntax you might want to know: F# gives you many ways to signal an error condition (like an empty list in this assignment), but your professor has asked you to use exception EmptyList when invalid input is given. That means he expects your code to "throw" or "raise" an exception when you encounter an error. In C# the term is "throw", but in F# the term is "raise", and the syntax looks like this:
if someErrorCondition then
raise EmptyList
// Or ...
match listThatShouldNotBeEmpty with
| [] -> raise EmptyList
| head::rest -> // Do something with head, etc.
That should take care of the next question you would have needed to ask. :-)
Update 2: You've edited your question to clarify another issue you're having, where your recursive function boils down to an empty list as the base case — yet your professor asked you to consider an empty list as an invalid input. There are two ways to solve this. I'll discuss the more complicated one first, then I'll discuss the easier one.
The more complicated way to solve this is to have two separate functions, an "outer" one and an "inner" one, for each of the functions you have been asked to define. In each case, the "outer" one checks whether the input is an empty list and throws an exception if that's the case. If the input is not an empty list, then it passes the input to the "inner" function, which does the recursive algorithm (and does NOT consider an empty list to be an error). So the "outer" function is basically only doing error-checking, and the "inner" function is doing all the work. This is a VERY common approach in professional programming, where all your error-checking is done at the "edges" of your code, while the "inner" code never has to deal with errors. It's therefore a good approach to know about — but in your particular case, I think it's more complicated than you need.
The easier solution is to rewrite your functions to consider a single-item list as the base case, so that your recursive functions never go all the way to an empty list. Then you can always consider an empty list to be an error. Since this is homework I won't give you an example based on your actual code, but rather an example based on a simple "take the sum of a list of integers" exercise where an empty list would be considered an error:
let rec sumNonEmptyList (input : int list) : int =
match input with
| [] -> raise EmptyList
| [x] -> x
| x::rest -> x + sumNonEmptyList rest
The syntax [x] in a match expression means "This matches a list with exactly one item in it, and assigns the name x to the value of that item". In your case, you'd probably be matching against Poly [] to raise an exception, Poly [a] as the base case, and Poly (a::af) as the "more than one item" case. (That's as much of a clue as I think I should give you; you'll learn better if you work out the rest yourself).

Operator overloading for discriminated union

I'm trying to write some numerical code that can work with either scalars or vectors (in this case it's the D and DV types respectively, from DiffSharp). Sometimes I want to be able to use either so I've defined a discriminated union for them:
type IBroadcastable =
| Scalar of D
| Vect of DV
A lot of operators are already overloaded for both of these types, so to use them on IBroadcastable I write add code like this to the union:
static member Exp x =
match x with
| Scalar x -> Scalar (exp x)
| Vect x -> Vect (exp x)
This seems very redundant. Is there any way I can use the operator on the union without having to write a new overload for it? Or I should I be using a different pattern (i.e. not a discriminated union)? An example of what I want to use this type for:
let ll (y: IBroadcastable) (theta: IBroadcastable) = y*theta-(exp theta)
The * and - will have more complicated behaviour (array broadcasting), which it makes sense to have to describe myself, but the exp operator is simple, as above. This needs to be a function since I want to be able to partially apply the y argument, get the gradient with DiffSharp, and maximise it with respect to the theta argument.
Fundamentally, since you're defining an abstraction, you need to define your operations in terms of that abstraction. That's a cost that has to be offset by the convenience it affords you elsewhere in your code.
What you may be wondering is if F# will let you cut on the boilerplate in your particular case. Apart from using the function keyword, not really, because both branches are really doing different things: the type of the bound variable x is different, and you're wrapping them in different union cases. If you were really doing the same thing, you could write it as such, for example:
type DU =
| A of float * float
| B of float * string
with
static member Exp = function
| A (b, _)
| B (b, _) -> exp b // only write the logic once
Your sample function ll is actually even more generic - it can work on anything that supports the operations it uses, even things that are not D or DV. If you define it using inline, then you will be able to call the function on both:
let inline ll y theta = y*theta-(exp theta)
The inline modifier lets F# use static member constraints, which can be satisfied by the required members when calling the function (unlike with normal generic functions that have to be compiled using what .NET runtime provides).
I expect this will not work for all your code, because you will need some operations that are specific to D and DV, but do not have generic F# function such as exp. You can actually access those using static member constraints, though this gets a bit hairy.
Assuming D and DV values both have a member Foo returning string, you can write:
let inline foo (x:^T) =
(^T : (member Foo : string) x)
let inline ll y theta = y*theta-(exp theta)+foo y
You can cut down on the boilerplate by doing something like this:
type IBroadcastable =
| Scalar of D
| Vect of DV
let inline private lift s v = function
| Scalar d -> Scalar (s d)
| Vect dv -> Vect (v dv)
type IBroadcastable with
static member Exp b = lift exp exp b
static member Cos b = lift cos cos b
...
and if you want to support binary operators, you can define a corresponding lift2 - but carefully consider whether it makes sense for the first argument to a binary operator to be a Scalar value and the second to be a Vect (or vice versa) - if not, then your discriminated union might not be an appropriate abstraction.

F# type mismatch while calling function

This code
let rec readNLines n list =
if n = 0 then
list
else
readNLines(n-1,readInt()::list)
ends with
Type mismatch. Expecting a 'a but given a 'a -> 'a
The resulting type would be infinite when unifying ''a' and
''a -> 'a' (using built-in F# compiler)
but runs ok when last line is changed to
readNLines(n-1,(readInt()::list))
or
readNLines(n-1)(readInt()::list)
Question is: Why? :|
Only the last version can work, because readNLines takes two arguments, but
readNLines (n - 1, readInt() :: list)
passes only one argument (which is a tuple consisting of an int and the list).
readNLines (n - 1) (readInt() :: list)
passes them as two separate arguments - the difference here is using the comma (tuple) and space (two arguments).
By the way, that becomes much clearer when you use more whitespace (as I did), because the individual elements are easier to identify.
Take a look at these two functions:
> let f1 a b = a + b
val f1 : a:int -> b:int -> int
> let f2 (a, b) = a + b
val f2 : a:int * b:int -> int
As you can see, they have slightly different types. In function f1 you partially apply the arguments (you'll see the term 'curried function' used here), in function f2 you pass in a tuple of arguments in one "go", or you can think of it as only ever having a single argument (an 'uncurried' function).
What you're doing is defining a function f1 style, but later calling it f2 style, which confuses the compiler.

How would you implement a beta-reduction function in F#?

I am writing a lambda calculus in F#, but I am stuck on implementing the beta-reduction (substituting formal parameters with the actual parameters).
(lambda x.e)f
--> e[f/x]
example of usage:
(lambda n. n*2+3) 7
--> (n*2+3)[7/n]
--> 7*2+3
So I'd love to hear some suggestions in regards to how others might go about this. Any ideas would be greatly appreciated.
Thanks!
Assuming your representation of an expression looks like
type expression = App of expression * expression
| Lambda of ident * expression
(* ... *)
, you have a function subst (x:ident) (e1:expression) (e2:expression) : expression which replaces all free occurrences of x with e1 in e2, and you want normal order evaluation, your code should look something like this:
let rec eval exp =
match exp with
(* ... *)
| App (f, arg) -> match eval f with Lambda (x,e) -> eval (subst x arg e)
The subst function should work as follows:
For a function application it should call itself recursively on both subexpressions.
For lambdas it should call itself on the lambda's body expression unless the lambda's argument name is equal to the identifier you want to replace (in which case you can just leave the lambda be because the identifier can't appear freely anywhere inside it).
For a variable it should either return the variable unchanged or the replacement-expression depending on whether the variable's name is equal to the identifier.

Resources