Why can't I define the following CoFixpoint? - type-inference

I am using:
$ coqtop -v
The Coq Proof Assistant, version 8.4pl5 (February 2015)
compiled on Feb 06 2015 17:44:41 with OCaml 4.02.1
I defined the following CoInductive type, stream:
$ coqtop
Welcome to Coq 8.4pl5 (February 2015)
Coq < CoInductive stream (A : Type) : Type :=
Coq < | Cons : A -> stream A -> stream A.
stream is defined
Coq < Check stream.
stream
: Type -> Type
Coq < Check Cons.
Cons
: forall A : Type, A -> stream A -> stream A
Then, I tried to define the following CoFixpoint definition, zeros:
Coq < CoFixpoint zeros : stream nat := Cons 0 zeros.
However, I got the following error instead:
Toplevel input, characters 38-39:
> CoFixpoint zeros : stream nat := Cons 0 zeros.
> ^
Error: In environment
zeros : stream nat
The term "0" has type "nat" while it is expected to have type
"Type".
I figured out that I have to explicitly instantiate the variable A:
Coq < CoFixpoint zeros : stream nat := Cons nat 0 zeros.
zeros is corecursively defined
Why doesn't the Coq infer the type of A by itself? How do I make it infer the type of A?

You need to declare A as implicit to ask Coq to infer it for you. There are a few ways of doing it:
Add the following declaration to your file: Set Implicit Arguments.. This will cause Coq to turn on automatic inference for arguments such as A for Cons, allowing you to write Cons 0 zeros.
Turn on implicit arguments just for Cons, without affecting the rest of the file:
Arguments Cons {A} _ _.
This declaration marks A as implicit and leaves the other two arguments as explicit.
Mark A as implicit in the definition of stream:
CoInductive stream {A : Type} : Type :=
| Cons : A -> stream A -> stream A.
I personally do not recommend doing this, however, as it will mark A as implicit for stream as well.
You can find more information about implicit arguments in the reference manual

Related

Antlr4: Mismatch input

My grammar:
qwe.g4
grammar qwe;
query
: COLUMN OPERATOR value EOF
;
COLUMN
: [a-z_]+
;
OPERATOR
: ('='|'>'|'<')
;
SCALAR
: [a-z_]+
;
value
: SCALAR
;
WS : [ \t\r\n]+ -> skip ;
Handling in Python code:
qwe.py
from antlr4 import InputStream, CommonTokenStream
from qweLexer import qweLexer
from qweParser import qweParser
conditions = 'total_sales>qwe'
lexer = qweLexer(InputStream(conditions))
stream = CommonTokenStream(lexer)
parser = qweParser(stream)
tree = parser.query()
for child in tree.getChildren():
print(child, '==>', type(child))
Running qwe.py outputs error when parsing (lexing?) value:
How to fix that?
I read some and suppose that there is something to do with COLUMN rule that also matches value...
Your COLUMN and SCALAR lexer rules are identical. When the LExer matches two rules, then the rule that recognizes the longest token will win. If the token lengths are the same (as the are here), the the first rule wins.
Your Token Stream will be COLUMN OPERATOR COLUMN
That's thy the query rule won't match.
As a general practice, it's good to use the grun alias (that the setup tutorial will tell you how to set up) to dump the token stream.
grun qwe tokens -tokens < sampleInputFile
Once that gives you the expected output, you'll probably want to use the grun tool to display parse trees of your input to verify that is correct. All of this can be done without hooking up the generated code into your target language, and helps ensure that your grammar is basically correct before you wire things up.

Algorithm W and monomorphic type coercion

I'm trying to write my own type inference algorithm for a toy language, but I'm running into a wall - I think algorithm W can only be used for excessively general types.
Here are the expressions:
Expr ::= EAbs String Expr
| EApp Expr Expr
| EVar String
| ELit
| EConc Expr Expr
The typing rules are straightforward - we proceed to use type variables for abstraction and application. Here are all possible types:
Type ::= TVar String
| TFun Type Type
| TMono
As you might have guessed, ELit : TMono, and more specifically, EConc :: TMono → TMono → TMono.
My issue comes from doing the actual type inference. When recursing down an expression structure, the general technique when seeing an EAbs is to generate a fresh type variable representing the newly bound variable, replace any occurrences of typing in our context with the (String : TVar fresh) judgment, then continue down the expression.
Now, when I hit EConc, I was thinking about taking the same approach - replace the free expression variables of the sub expressions with TMon in the context, then type-infer the sub expressions, and take the most-general unifier of the two results as the main substitution to return. However, when I try this with an expression like EAbs "x" $ EConc ELit (EVar "x"), I get the incorrect TFun (TVar "fresh") TMon.
You need to use mgu to coerce sub-expressions. If you directly manipulate the context to affect sub expressions, you don't know how that affects earlier types. Use mgu to get the substitution that unifies sub expressions to TMon, then compose that substitution in the result.

printing a float with runtime-selectable precision

This is similar to this question but not exactly the same.
i naively tried this:
let s prec = "%." ^ (string_of_int prec) ^ "f" in
Printf.printf (s 2) 1.23
but this is rejected, as well as replacing ^ by ^^. is there any way to do this?
Since format string are type-safe they should be known at compile time. You can't take an arbitrary string and use it as a format string. This restriction still allows you to build formats from pieces, you just shouldn't forget to call format_of_string function, and make sure that all your formats are static, and resulting formats has the same type.
But, your particular case is already addressed by the formats, so you don't need to do anything fancy here. There is * specifier, that does exactly what you want:
# printf "%.*f" 10 1.0;;
1.0000000000- : unit = ()
# printf "%.*f" 1 1.0;;
1.0- : unit = ()
There is also Scanf.format_from_string that allows you to build arbitrary formats from dynamic strings. The following program demonstrates the flexibility of formats in OCaml:
let () =
print_endline "Floating point format: ";
let f = match read_line () with
| "engineering" -> "%e"
| "regular" -> "%f"
| "pretty" -> "%g"
| user -> user in
let fmt =
try Scanf.format_from_string f "%f"
with exn -> invalid_arg "Unrecognized format" in
Printf.printf (fmt^^"\n") (4. *. atan 1.)
Example:
ivg$ ocaml formats.ml
Floating point format:
pi = %.16f
pi = 3.1415926535897931

is this regular grammar- S -> 0S0/00?

Let L denotes the language generated by the grammar S -> 0S0/00. Which of the following is true?
(A) L = 0+
(B) L is regular but not 0+
(C) L is context free but not regular
(D) L is not context free
HI can anyone explain me how the language represented by the grammar S -> 0S0/00 is regular? I know very well the grammar is context free but not sure how can that be regular?
If you mean the language generated by the grammar
S -> 0S0
S -> 00
then it should be clear that it is the same language as is generated by
S -> 00S
S -> 00
which is a left regular grammar, and consequently generates a regular language. (Some people would say that a left regular grammar can only have a single terminal in each production, but it is trivial to create a chain of aN productions to produce the same effect.)
It should also be clear that the above differs from
S -> 0S
S -> S
We know that a language is regular if there exists a DFA (deterministic finite automata) that recogognizes it, or a RE (Regular expression). Either way we can see here that your grammar generates word like : 00, 0000, 000000, 00000000.. etc so it's words that starts and ends with '0' and with an even number of zeroes greater or equal than length two.
Here's a DFA for this grammar
Also here is a RE (Regular expression) that recognizes the language :
(0)(00)*(0)
Therefore you know this language recognized by this grammar is regular.
(Sorry if terms aren't 100% accurate, i took this class in french so terms might differ a bit) let me know if you have any other questions!
Consider first the definition of a regular grammar here
https://www.cs.montana.edu/ross/theory/contents/chapter02/green/section05/page04.xhtml
So first we need a set N of non terminal symbols (symbols that can be rewritten as a combination of terminal and non-terminal symbols), for our example N={S}
Next we need a set T of terminal symbols (symbols that cannot be replaced), for our example T={0}
Now a set P of grammer rules that fit a very specific form (see link), for L we see that P={S->0S0,S->00}. Both of these rules are of regular form (meaning each non-terminal can be replaced with a terminal, a terminal then a non-terminal, or the empty string, see link for more info). So we have our rules.
Now we just need a starting symbol X, we can trivally say that our starting symbol is S.
Therefore the tuple (N={S},T={0},P={S->0S0,S->00},X=S) fits the requirements to be defined a regular grammar.
We don't need the machinery of regular grammars to answer your question. Just note the possible derivations all look like this:
S -> (0 S 0) -> 0 (0 S 0) 0 -> 0 0 (0 S 0) 0 0 -> ... -> 0...0 (0 0) 0...0
\_ _/ \_ _/
k k
Here I've added parens ( ) to show the result of the previous expansion of S. These aren't part of the derived string. I.e. we substitute S with 0 S 0 k >= 0 times followed by a single substitution with 00.
From this is should be easy to see L is the set of strings of 0's of length 2k + 2 for some integer k >= 0. A shorthand notation for this is
L = { 02m | m >= 1 }
In words: The set of all even length strings of zeros excluding the empty string.
To prove L is regular, all we need is a regular expression for L. This is easy: (00)+. Or if you prefer, 00(00)*.
You might be confused because a small change to the grammar makes its language context free but not regular:
S -> 0S1/01
This is the more complex language { 0m 1m | m >= 1 }. It's straightforward to show this isn't a regular language using the Pumping Lemma.

OCaml: Why I can't use this operator infix?

I defined a custom equality operator (the definition is not really important so I will insert dummy stuff):
let ( ~=~ ) a b = true
If I try to use it infix:
if a ~=~ b then 1 else 2
I get the following error:This expression is not a function; it cannot be applied.
I can fix this either by renaming the operator from ~=~ to =~ or by calling it as a function: if (~=~) a b then 1 else 2.
This seems that is a general problem with operators that start with ~.
My question is why I can't use such operators infix? Is anything special about ~ symbol?
Note: I already went through documentation but I couldn't find anything relevant. Maybe I missed something?
In OCaml, whether an operator is infix or prefix is determined by its first character.
In you case, the character '~' is for prefix: by let (~=~) a b = ..., you are defining a prefix operator. ~=~ a is a valid expression, and returns a function.
In addition to infix or prefix, infix operator associativity (left or right) and operator precedences (which of + and * has stronger?) are syntactically determined by the first character of the operator.
This sounds ugly, since you cannot have control of your fancy operators characteristics, but it makes easier to read OCaml source code by someone else with lots of strange custom operators.
Here is the table of chars for operators:
The first char : prefix/infix/connectivity power/left-or-right
! ~ ? : prefix
= < > | & $ : infix0, left
# ^ : infix1, right
+ - : infix2, left
* / : infix3, left ( ** is exceptional. It is right assoc and have power 4)
By lexical conventions of ocaml ~ is reserved for prefix operators, see
http://caml.inria.fr/pub/docs/manual-ocaml/lex.html#infix-symbol