Using TypeClass Instances Within Typeclasses - typeclass

I am trying to define two instances of a type class, one of which will use the other's instance. However, unless I bind the function's name outside of the second definition Coq is unable to determine it should use the type class instance from bexp (take a look at the comment for dirty hack). Is there a way to avoid this sort of hack in Coq?
Class Compilable ( A : Type ) := { compile : A -> bool }.
Inductive cexp : Type :=
| CAnd : cexp -> cexp -> cexp
| COr : cexp -> cexp -> cexp
| CProp : bexp -> cexp.
Instance: Compilable bexp :=
{ compile :=
fix compile b :=
match b with
(* elided *)
end
}.
Definition compile2 := compile.
Instance: Compilable cexp :=
{ compile :=
fix compile c :=
match c with
| CAnd x y => (compile x) && (compile y)
| COr x y => (compile x) || (compile y)
| CProp e => (compile2 e) (* <-- dirty hack *)
end
}.

This can be fixed if we replace compile with some other name (rec) like so:
Instance: Compilable cexp :=
{ compile :=
fix rec c :=
match c with
| CAnd x y => (rec x) && (rec y)
| COr x y => (rec x) || (rec y)
| CProp e => (compile e)
end
}.
In this comment the OP pointed out that Haskell easily deals with this situation. To understand the reason why Coq does not do it let us take a look at the type of compile:
About compile.
compile : forall A : Type, Compilable A -> A -> bool
Arguments A, Compilable are implicit and maximally inserted
We can see that Coq is more explicit about how typeclasses work. When you call compile e Coq sort of inserts placeholders standing for the implicit arguments like so #compile _ _ e (see these slides, pages 21-25 for more detail). But with fix compile c you shadowed the previous binding, hence the type error.

Related

Fixpoint functions in Type Class Instances

I am trying to use a fixpoint style function in the context of a type class instance but it doesn't seem to work. Is there something extra I have to do to make this work? For the time being I've used a hack of moving the function outside the type class and explicitly declaring it Fixpoint. This seems awful, however.
Here's the short example:
Inductive cexp : Type :=
| CAnd : cexp -> cexp -> cexp
| COr : cexp -> cexp -> cexp
| CProp : bool -> cexp.
Class Propable ( A : Type ) := { compile : A -> Prop }.
Instance: Propable cexp :=
{ compile c :=
match c with
| CAnd x y => (compile x) /\ (compile y)
| COr x y => (compile x) \/ (compile y)
| CProp _ => False
end
}.
This fails with:
Error: Unable to satisfy the following constraints:
In environment:
c, x, y : cexp
?Propable : "Propable cexp"
What does one have to do to make this work?
You can use fix to do that:
Instance: Propable cexp :=
{ compile := fix compile c :=
match c with
| CAnd x y => (compile x) /\ (compile y)
| COr x y => (compile x) \/ (compile y)
| CProp _ => False
end
}.
Let me illustrate how one can come up with it. Let's take the following piece of code:
Fixpoint silly n :=
match n with
| 0 => 0
| S n => silly n
end.
Fixpoint here is a vernacular command which makes the definition a little bit easier on the eyes, but it conceals what is going on here. It turns out that what Coq actually does is something like this:
Definition silly' :=
fix self n :=
match n with
| 0 => 0
| S n => self n
end.
You can verify it by using Print silly. after the definition.

Coq: usage of `PartialOrder` typeclass

I am trying to define lexicographic ordering on strings over posets, but I'm not completely sure how to use the PartialOrder typeclass.
Require Import List RelationClasses.
Fail Inductive lex_leq {A : Type} `{po : PartialOrder A} : list A -> list A -> Prop :=
| lnil: forall l, lex_leq nil l
| lcons:
forall (hd1 hd2 : A) (tl1 tl2 : list A),
hd1 <= hd2 -> (* error *)
(hd1 = hd2 -> lex_leq tl1 tl2) ->
lex_leq (hd1 :: tl1) (hd2 :: tl2).
Partial output:
The term "hd1" has type "A" while it is expected to have type "nat".
Clearly <= is the wrong notation to use here; I'm wondering how I can obtain an ordering relation from my po instance.
One can bind the names explicitly to make things more obvious. Before we can do this we need to tell Coq not to complain about unbound variables using the Generalizable Variables command:
From Coq Require Import List RelationClasses.
Generalizable Variables A eqA R.
Inductive lex_leq `{PartialOrder A eqA R} : list A -> list A -> Prop :=
| lnil: forall l, lex_leq nil l
| lcons:
forall (hd1 hd2 : A) (tl1 tl2 : list A),
R hd1 hd2 ->
(hd1 = hd2 -> lex_leq tl1 tl2) ->
lex_leq (hd1 :: tl1) (hd2 :: tl2).
You can find more information in the manual (here).

What is wrong with 100000 factorial using ContinuationMonad?

It is powerful technique using recursion because its strong describable feature. Tail recursion provides more powerful computation than normal recursion because it changes recursion into iteration. Continuation-Passing Style (CPS) can change lots of loop codes into tail recursion. Continuation Monad provides recursion syntax but in essence it is tail recursion, which is iteration. It is supposed to reasonable use Continuation Monad for 100000 factorial. Here is the code.
type ContinuationBuilder() =
member b.Bind(x, f) = fun k -> x (fun x -> f x k)
member b.Return x = fun k -> k x
member b.ReturnFrom x = x
(*
type ContinuationBuilder =
class
new : unit -> ContinuationBuilder
member Bind : x:(('d -> 'e) -> 'f) * f:('d -> 'g -> 'e) -> ('g -> 'f)
member Return : x:'b -> (('b -> 'c) -> 'c)
member ReturnFrom : x:'a -> 'a
end
*)
let cont = ContinuationBuilder()
//val cont : ContinuationBuilder
let fac n =
let rec loop n =
cont {
match n with
| n when n = 0I -> return 1I
| _ -> let! x = fun f -> f n
let! y = loop (n - 1I)
return x * y
}
loop n (fun x -> x)
let x2 = fac 100000I
There is wrong message: "Process is terminated due to StackOverflowException."
What is wrong with 100000 factorial using ContinuationMonad?
You need to compile the project in Release mode or check the "Generate tail calls" option in project properties (or use --tailcalls+ if you're running the compiler via command line).
By default, tail call optimization is not enabled in Debug mode. The reason is that, if tail-calls are enabled, you will not see as useful information about stack traces. So, disabling them by default gives you more pleasant debugging experience (even in Debug mode, the compiler optimizes tail-recursive functions that call themselves, which handles most situations).
You probably need to add this memeber to your monad builder:
member this.Delay(mk) = fun c -> mk () c

Generating parameterized F# quotations

Let's say we have a simple F# quotation:
type Pet = { Name : string }
let exprNonGeneric = <## System.Func(fun (x : Pet) -> x.Name) ##>
The resulting quotation is like:
val exprNonGeneri : Expr =
NewDelegate (System.Func`2[[FSI_0152+Pet, FSI-ASSEMBLY, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null],[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]],
x, PropertyGet (Some (x), System.String Name, []))
Now I want to generalize it, so I instead of type "Pet" and property "Name" I could use an arbitrary type and method/property defined on it. Here is what I am trying to do:
let exprGeneric<'T, 'R> f = <## System.Func<'T, 'R>( %f ) ##>
let exprSpecialized = exprGeneric<Pet, string> <# (fun (x : Pet) -> x.Name) #>
The resulting expression is now different:
val exprSpecialized : Expr =
NewDelegate (System.Func`2[[FSI_0152+Pet, FSI-ASSEMBLY, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null],[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]],
delegateArg,
Application (Lambda (x,
PropertyGet (Some (x), System.String Name, [])),
delegateArg))
As you can see, the difference between the first and the second expression is that in first case the top level NewDelegate expression contains PropertyGet, while the second expression wraps PropertyGet in a Application/Lambda expression. And when I pass this expression to an external code it does not expect such expression structure and fails.
So I need some way to build a generalized version of quotation, so when it gets specialized, the resulting quotation is an exact match of <## System.Func(fun (x : Pet) -> x.Name) ##>. Is this possible? Or it there only choice to manually apply pattern matching to a generated quotation and transform it to what I need?
UPDATE. As a workaround I implemented the following adapter:
let convertExpr (expr : Expr) =
match expr with
| NewDelegate(t, darg, appl) ->
match (darg, appl) with
| (delegateArg, appl) ->
match appl with
| Application(l, ldarg) ->
match (l, ldarg) with
| (Lambda(x, f), delegateArg) ->
Expr.NewDelegate(t, [x], f)
| _ -> expr
| _ -> expr
| _ -> expr
It does the job - I can now convert expression from 1st to 2nd form. But I am interested in finding out if this can be achieved in a simple way, without traversing expression trees.
I don't think it will be possible to do this; in the second case, you are plugging in the expression <# (fun (x : Pet) -> x.Name) #>, which is represented using a Lambda node, into the hole in the other expression. The compiler does not simplify expressions during this plugging process, so the Lambda node won't be removed no matter what you do.
However your pattern matching workaround can be greatly simplified:
let convertExpr = function
| NewDelegate(t, [darg], Application(Lambda(x,f), Var(arg)))
when darg = arg -> Expr.NewDelegate(t, [x], f)
| expr -> expr
In fact, your more complicated version is incorrect. This is because the delegateArg in your innermost pattern is not matching against the value of the previously bound delegateArg identifier from the outer pattern; it is a new, freshly bound identifier which also happens to be called delegateArg. In fact, the outer delegateArg identifier has type Var list while the inner one has type Expr! However, given the limited range of expression forms generated by the compiler your broken version may not be problematic in practice.
EDIT
Regarding your followup questions, if I understand you correctly it may not be possible to achieve what you want. Unlike C#, where x => x + 1 could be interpreted as having a type of either Func<int,int> or Expression<Func<int,int>>, in F# fun x -> x + 1 is always of type int->int. If you want to get a value of type Expr<int->int> then you generally need to use the quotation operator (<# #>).
There is one alternative that may be of use, however. You can use the [<ReflectedDefinition>] attribute on let bound functions to make their quotations available as well. Here's an example:
open Microsoft.FSharp.Quotations
open Microsoft.FSharp.Quotations.ExprShape
open Microsoft.FSharp.Quotations.Patterns
open Microsoft.FSharp.Quotations.DerivedPatterns
let rec exprMap (|P|_|) = function
| P(e) -> e
| ShapeVar(v) -> Expr.Var v
| ShapeLambda(v,e) -> Expr.Lambda(v, exprMap (|P|_|) e)
| ShapeCombination(o,l) -> RebuildShapeCombination(o, l |> List.map (exprMap (|P|_|)))
let replaceDefn = function
| Call(None,MethodWithReflectedDefinition(e),args)
-> Some(Expr.Applications(e, [args]))
| _ -> None
(* plugs all definitions into an expression *)
let plugDefs e = exprMap replaceDefn e
[<ReflectedDefinition>]
let f x = x + 1
(* inlines f into the quotation since it uses the [<ReflectedDefinition>] attribute *)
let example = plugDefs <# fun y z -> (f y) - (f 2) #>

Would you please explain OCaml functors to me? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
In Functional Programming, what is a functor?
I don't know much about OCaml, I've studied F# for some time and quite understand it.
They say that F# misses functor model, which is present in OCaml. I've tried to figure out what exactly functor is, but wikipedia and tutorials didn't help me much.
Could you please illuminate that mystery for me? Thanks in advance :)
EDIT:
I've caught the point, thx to everyone who helped me. You can close the question as exact duplicate of: In Functional Programming, what is a functor?
If you come from an OOP universe, then it probably helps to think of a module as analogous to a static class. Similar to .NET static classes, OCaml module have constructors; unlike .NET, OCaml modules can accept parameters in their constructors. A functor is a scary sounding name for the object you pass into the module constructor.
So using the canonical example of a binary tree, we'd normally write it in F# like this:
type 'a tree =
| Nil
| Node of 'a tree * 'a * 'a tree
module Tree =
let rec insert v = function
| Nil -> Node(Nil, v, Nil)
| Node(l, x, r) ->
if v < x then Node(insert v l, x, r)
elif v > x then Node(l, x, insert v r)
else Node(l, x, r)
Fine and dandy. But how does F# know how to compare two objects of type 'a using the < and > operators?
Behind the scenes, its doing something like this:
> let gt x y = x > y;;
val gt : 'a -> 'a -> bool when 'a : comparison
Alright, well what if you have an object of type Person which doesn't implement that particular interface? What if you wanted to define the sorting function on the fly? One approach is just to pass in the comparer as follows:
let rec insert comparer v = function
| Nil -> Node(Nil, v, Nil)
| Node(l, x, r) ->
if comparer v x = 1 then Node(insert v l, x, r)
elif comparer v x = -1 then Node(l, x, insert v r)
else Node(l, x, r)
It works, but if you're writing a module for tree operations with insert, lookup, removal, etc, you require clients to pass in an ordering function everytime they call anything.
If F# supported functors, its hypothetical syntax might look like this:
type 'a Comparer =
abstract Gt : 'a -> 'a -> bool
abstract Lt : 'a -> 'a -> bool
abstract Eq : 'a -> 'a -> bool
module Tree (comparer : 'a Comparer) =
let rec insert v = function
| Nil -> Node(Nil, v, Nil)
| Node(l, x, r) ->
if comparer.Lt v x then Node(insert v l, x, r)
elif comparer.Gt v x then Node(l, x, insert v r)
else Node(l, x, r)
Still in the hypothetical syntax, you'd create your module as such:
module PersonTree = Tree (new Comparer<Person>
{
member this.Lt x y = x.LastName < y.LastName
member this.Gt x y = x.LastName > y.LastName
member this.Eq x y = x.LastName = y.LastName
})
let people = PersonTree.insert 1 Nil
Unfortunately, F# doesn't support functors, so you have to fall back on some messy workarounds. For the scenario above, I would almost always store the "functor" in my data structure with some auxillary helper functions to make sure it gets copied around correctly:
type 'a Tree =
| Nil of 'a -> 'a -> int
| Node of 'a -> 'a -> int * 'a tree * 'a * 'a tree
module Tree =
let comparer = function
| Nil(f) -> f
| Node(f, _, _, _) -> f
let empty f = Nil(f)
let make (l, x, r) =
let f = comparer l
Node(f, l, x, r)
let rec insert v = function
| Nil(_) -> make(Nil, v, Nil)
| Node(f, l, x, r) ->
if f v x = -1 then make(insert v l, x, r)
elif f v x = 1 then make(l, x, insert v r)
else make(l, x, r)
let people = Tree.empty (function x y -> x.LastName.CompareTo(y.LastName))
Functors are modules parameterized by modules, i.e. a reflection from modules to modules (ordinary function is reflection from values to values, polymorphic function is reflection from types to ordinary functions).
See also ocaml-tutorial on modules.
Examples in the manual are helpful too.
Check out this data structures in ocaml course:
http://www.cs.cornell.edu/Courses/cs3110/2009fa/lecturenotes.asp
the functor lecture:
http://www.cs.cornell.edu/Courses/cs3110/2009fa/lectures/lec10.html
and the splay tree implementation using functor:
http://www.cs.cornell.edu/Courses/cs3110/2009fa/recitations/rec-splay.html

Resources