How to define Notation format in Coq using { - notation

I defined this notation:
Definition Id (n:nat):= n.
Notation "'ID' { n } ":= (Id n) (no associativity, at level 99).
Which works just fine. Now I want to add format to change the line breaks and alignment. Suppose I want to Print something like this:
ID
{ n }
So I tried the following notation:
Notation "'ID' { n } ":= (Id n) (no associativity, at level 99,
format "'ID' '//' { n } ").
In which case I get
Warning: Invalid character '{' at beginning of identifier "{".
So How am I supposed to define a format using {?

Simply remove the curly braces from the format:
Definition Id (n : nat) := n.
Notation "'ID' { n } " := (Id n)
(no associativity, at level 99,
format "'ID' '//' n " ).
Check (ID { 4 }).
I'm not sure this is intentional or a bug. However, as the Coq user's manual says, curly braces { } have a special status in notations and are treated differently from other kinds braces. Thus, if you want to do the same with, say, [ ], you need to include the brackets in the format:
Definition Id (n : nat) := n.
Notation "'ID' [ n ] " := (Id n)
(no associativity, at level 99,
format "'ID' '//' [ n ] " ).
Check (ID [ 4 ]).

Related

Resolving PREDICT/PREDICT conflicts in LL(1)

I'm working on a simple LL(1) parser generator, and I've run into an issue with PREDICT/PREDICT conflicts given certain input grammars. For example, given an input grammar like:
E → E + E
| P
P → 1
I can remove out the left recursion from E, replacing it with a roughly equivalent right recursive rule, thus arriving at the grammar:
E → P E'
E' → + E E'
| ε
P → 1
Next, I can compute the relevant FIRST and FOLLOW sets for the grammar, and end up with the following:
FIRST(E) = { 1 }
FIRST(E') = { +, ε }
FIRST(P) = { 1 }
FOLLOW(E) = { +, EOF }
FOLLOW(E') = { +, EOF }
FOLLOW(P) = { +, EOF }
And finally, using PREDICT(A → α) = { FIRST(α) - ε } ∪ (FOLLOW(A) if ε ∈ FIRST(α) else ∅) to construct the PREDICT sets for the grammar, the resulting sets are as follows.
PREDICT(1. E → P E') = { 1 }
PREDICT(2. E' → + E E') = { +, EOF }
PREDICT(3. E' → ε) = { +, EOF }
PREDICT(4. P → 1) = { 1 }
So this is where I run into the conflict that PREDICT(2) = PREDICT(3), and thus, I cannot produce a parse table as the grammar is not LL(1), since parser wouldn't be able to choose which rule should be applied.
What I'm really wondering is whether it's possible to resolve the conflict or factor the grammar such that the conflict can be avoided, and produce a legal LL(1) grammar, without having to directly modify the original input grammar.
The problem here is that your original grammar is ambiguous.
E → E + E
E → P
means that P + P + P can be parsed either as (P + P) + P or P + (P + P). Eliminating left recursion doesn't fix the ambiguity, so the modified grammar is also ambiguous. And ambiguous grammars can't be LL(k) (or, for that matter, LR(k)).
So you need to make the grammar unambiguous:
E → E + P
E → P
(That's the common left-associative version.) Once you eliminate left recursion, you end up with:
E → P E'
E' → + P E'
| ε
Now + is not in FOLLOW(E').
(The example is drawn straight from the Dragon book, but simplified; it's example 4.8 in the rather battered old copy I have.)
It's worth noting that the transformation used here preserves the set of strings derived by the grammar, but not the derivation. The parse tree which results from the modified grammar is effectively right-associative, so it will need to be reprocessed to recover the desired parse. This fact is rather briefly mentioned by the Dragon book authors:
Although left-recursion elimination and left factoring are easy to do, they make the resulting grammar hard to read and difficult to use for translation purposes. (My emphasis)
They go on to suggest that operator precedence parsing can be used for expressions, and then mention that if an LR parser generator is available, dividing the grammar into a predictive part and an operator-precedence part is no longer necessary.

Why won't this Mathematica code maximize?

f[n_] := ((A*n^a)^(1/s) +
c*(B*(a*c*(B/A)^(1/s)*n^(1 - (a/s)))^(-(a*s)/(a - s)))^(1/s))^s +
b*log (1 - n - ((a*c*(B/A)^(1/s)*n^(1 - (a/s)))^(-(a*s)/(a - s))))
d/dn (f (n))
d/dn (f[n])
D[f[n], n]
solve (D[f[n], n] = 0)
0
Solve[D[f[n], n] = 0, n]
Solve[0, n]
Maximize[f[n], n]
Maximize[b log (1 - n - (a (B/A)^(1/s) c n^(1 - a/s))^(-((a s)/(a - s)))) + ((A n^a)^(1/s)
+ c (B (a (B/A)^(1/s) c n^(1 - a/s))^(-((a s)/(a - s))))^(1/s))^s, n]
I am not getting anything returning for any of these functions. Any idea why?
Attaching a photo of the mathematica script:
First of all, you're using solve with a lowercase, which is just an undefined variable. To use the function Solve you need to write it with a capital letter. In the same way, you have to write Log with a capital letter, not a lower-case letter, since it's a built in function.
Second, your open parenthesis is not a bracket. Functions in Mathematica require brackets, like Solve[ ... ], not Solve( ).
Third, you're using = instead of ==. The single equals = is used to store variables, the double equals == is used to represent equality.
See if you can get it to work after remedying these errors.

Converting terenary and boolean operators from infix to postfix

How can I convert these two examples from infix to postfix?
Example 1:
max = (a > b) ? a : b
Example 2:
(a != 0) ? ((b != 0) ? True : False) : False
For both expressions, I thought I would just have to remove the brackets. However, when I try to convert back from postfix to infix, the expression is invalid. I know how to do simple operations:
Infix: (((a + b) * (c + d) + a) * c - 6) * b
Postfix: a b + c d + * a + c * 6 - b *
...but I'm not sure how to convert max and boolean expressions.
Instead of thinking about '+', '-', and '*' as operations apart from
boolean operators or max / min functions, I think you could understand
the problem better by simply saying, "All of these are operators with 2 operands --
ie, they are binary operators."
Then, the problem is setting up your expression tree so that the root is an
operator ('+', '-', 'max' or whatever), and the children are operands. Producing
infix or postfix is simply a question of how you traverse the expression tree.

Extending Immutable types (or: fast cache for immutable types) in OCaml

I have a recursive immutable data structure in ocaml which can be simplified to something like this:
type expr =
{
eexpr : expr_expr;
some_other_complex_field : a_complex_type;
}
and expr_expr =
| TInt of int
| TSum of (expr * expr)
| TMul of (expr * expr)
It's an AST, and sometimes it gets pretty complex (it's very deep).
there is a recursive function that evaluates an expression. For example, let's say,
let rec result expr =
match expr.eexpr with
| TInt i -> i
| TSum (e1, e2) -> result e1 + result e2
| TMul (e1, e2) -> result e1 * result e2
Now suppose I am mapping an expression to another expression, and I need to constantly check the result of an expr, sometimes more than once for the same expr, and sometimes for expressions that were recently mapped by using the pattern
{ someExpr with eexpr = TSum(someExpr, otherExpr) }
Now, the result function is very lightweight, but running it many times for a deep AST will not be very optimized. I know I could cache the value using a Hashtbl, but AFAIK the Hashtbl will only do structural equality, so it will need to traverse my long AST anyway.
I know the best option would be to include a probably immutable "result" field in the expr type. But I can't.
So is there any way in Ocaml to cache a value to an immutable type, so I don't have to calculate it eagerly every time I need it ?
Thanks!
Hash-cons the values of expr_expr. By doing this structurally equal values in your program will share exactly the same memory representation and you can substitute structural equality (=) by physical equality (==).
This paper should get you quickly started on hash-consing in OCaml.
You can use the functorial interface to control the kind of equality used by the hash table. I believe the semantics of (==) are legitimate for your purposes; i.e., if A == B then f A = f B for any pure function f. So you can cache the results of f A. Then if you find a B that's physically equal to A, the cached value is correct for B.
The downside of using (==) for hashing is that the hash function will send all structurally equal objects to the same hash bucket, where they will be treated as distinct objects. If you have a lot of structurally equal objects in the table, you get no benefit from the hashing. The behavior degenerates to a linear search.
You can't define the hash function to work with physical addresses, because the physical addresses can be changed at any time by the garbage collector.
However, if you know your table will only contain relatively few large-ish values, using physical equality might work for you.
I think you can merge the two ideas above : use hash-consing-like techniques to get the hash of the "pure expression" part of your data, and use this hash as key in the memoization table for the eval function.
Of course this only works when your eval function indeed only depends on the "pure expression" part of the function, as in the example you gave. I believe that is a relatively general case, at least if you restrict yourself to storing the successful evaluations (that won't, for example, return an error including some location information).
Edit: a small proof of concept:
type 'a _expr =
| Int of int
| Add of 'a * 'a
(* a constructor to avoid needing -rectypes *)
type pure_expr = Pure of pure_expr _expr
type loc = int
type loc_expr = {
loc : loc;
expr : loc_expr _expr;
pure : pure_expr (* or any hash_consing of it for efficiency *)
}
(* this is where you could hash-cons *)
let pure x = Pure x
let int loc n =
{ loc; expr = Int n; pure = pure (Int n) }
let add loc a b =
{ loc; expr = Add (a, b); pure = pure (Add(a.pure, b.pure)) }
let eval =
let cache = Hashtbl.create 251 in
let rec eval term =
(* for debug and checking memoization *)
Printf.printf "log: %d\n" term.loc;
try Hashtbl.find cache term.pure with Not_found ->
let result =
match term.expr with
| Int n -> n
| Add(a, b) -> eval a + eval b in
Hashtbl.add cache term.pure result;
result
in eval
let test = add 3 (int 1 1) (int 2 2)
# eval test;;
log: 3
log: 2
log: 1
- : int = 3
# eval test;;
log: 3
- : int = 3

how to code this recursive grammar?

I have the following grammar :
S -> S{S}S | null
Here null means nothing to be there in place of S.
I need to generate all possible strings of 2n brackets generated by this grammar.
I have tried to code it but the program runs out of memory. Could someone please help me code this grammar for 2n number of brackets?
Thanks a lot in advance
First, prove that this grammar generates all strings of balanced curly braces.
(Hint: Start by proving S -> S{S} | null generates all such strings.)
Then just write a function to generate all of those:
function generate(num_opens, num_closes, string_so_far, N)
if (num_opens + num_closes == N)
print string_so_far;
return;
if (num_opens > num_closes)
generate(num_opens, num_closes+1, string_so_far . '}', N)
generate(num_opens+1, num_closes, string_so_far . '{', N)
generate(0, 0, N)
This may or may not be in the "spirit" of the question.
Some psuedocode for you:
function grammar: S(string), n(int), generatedStrings(collection)
if (|S| == 2*n)
// Store in generatedStrings
return
else if (|S| > 2*n)
return
grammar(S + '{}', n, generatedStrings)
grammar(S +'{'+ S +'}', n, generatedStrings)
grammar(S +'{'+ S +'}'+ S, n, generatedStrings)
grammar('{'+ S +'}'+ S, n, generatedStrings)
grammar('{'+ S +'}', n, generatedStrings)
grammar('{}'+ S, n, generatedStrings)
Then you'll just need some mechanism to make sure you don't add duplicates to the set of generated strings. I'd use a set-type data structure (in other words, a structure that only allows one of each value to be stored) for that.

Resources