How does one compute/create a concrete/actual string in coq to pass to functions or store in a variable/identifier? - coq

I simply want to create a concrete string and do stuff with it as if coq was a programming language. How do I create a string?
I tried:
(* From Coq Require Export String. *)
(* Compute "hello". *)
(* Require Import Ascii String. *)
(* Compute "hello". *)
(* Open Local Scope char_scope. *)
(* Compute "hello". *)
(* Example Space := " ". *)
Module Export StringSyntax.
End StringSyntax.
(* Example HelloWorld := " ""Hello world!"" ".
Compute "hello". *)
Print "hello".
which none work the way:
Compute 2.
displays:
= 2
: nat
How do I create an actual string or symbol so I can pass it to functions I create etc?
super hacky....but wish it was different:
Inductive my_parens : Type :=
| LeftMyParen
| RightMyParen.
Notation "<<<<" := LeftMyParen.
Notation ">>>>" := RightMyParen.
Compute LeftMyParen.
Compute RightMyParen.
out
= <<
: my_parens
= <<<<
: my_parens
= >>>>
: my_parens

You just had the scope wrong:
Require Import Coq.Strings.String.
Open Scope string_scope. (* NB *)
Compute "Hello, world!".

If your desperate from (finite) symbols you can do this:
Inductive my_parens : Type :=
| LeftMyParen
| RightMyParen.
Notation "<<<<" := LeftMyParen.
Notation ">>>>" := RightMyParen.
Compute LeftMyParen.
Compute RightMyParen.
out
= <<
: my_parens
= <<<<
: my_parens
= >>>>
: my_parens

also works:
Require Import String.
Example HI : string := "abc".

Related

Recovering the name of a variable in Maple

I am programming a procedure in Maple. This procedure receive a list of vector fields (from the ``DifferentialGeometry'' package). I want that in the output they appear, together with the performed computations, the name of the vector fields introduced by the user.
During the procedure I refer to them by the name I have given to the parameter, but I don't actually know the "names of the variables". Is there a way to recover them? I have being looking for in the Maple documentation and in the DGinfo help, but I didn't get anything.
EXAMPLE ADDED
I have simplified the problem to the following. Consider the code:
with(DifferentialGeometry);
DGsetup([x, u], M);
X := evalDG(D_u*x+2*D_x);
myproc := proc (var)
return evalDG(var+D_u)
end proc;
myproc(X)
The output is
But I want modify the code in such a way that the output were something like
X+D_u is 2 D_x + (1+x) D_u
That is, I want to use the name ("X") of the variable in the output, not only the value (2 D_x + x D_u).
Thank you for your time.
Here is one way of handling your example.
restart;
with(DifferentialGeometry):
DGsetup([x, u], M):
myproc := proc(var::uneval) local evar;
evar := eval(var);
return evalDG(var+D_u) = evalDG(evar+D_u);
end proc:
X := evalDG(D_u*x+2*D_x):
myproc(X);
X + D_u = 2 D_u + (1 + x) D_u
Here is a variant on that idea, with two such parameters on the procedure, but also handling then in a more general manner.
restart;
with(DifferentialGeometry):
DGsetup([x, u], M):
myproc := proc(var1::uneval, var2::uneval)
local evars, res;
evars := [var1=eval(var1), var2=eval(var2)];
res := var1 + var2 + D_u;
return res = evalDG(eval(res, evars));
end proc:
X1 := evalDG(D_u*x+2*D_x):
X2 := evalDG(D_u*x+3*D_x):
myproc(X1, X2);
X1 + X2 + D_u = 5 D_x + (1 + 2 x) D_x

How to generate arbitrary instances of a language given its concrete syntax in Rascal?

Given the concrete syntax of a language, I would like to define a function "instance" with signature str (type[&T]) that could be called with the reified type of the syntax and return a valid instance of the language.
For example, with this syntax:
lexical IntegerLiteral = [0-9]+;
start syntax Exp
= IntegerLiteral
| bracket "(" Exp ")"
> left Exp "*" Exp
> left Exp "+" Exp
;
A valid return of instance(#Exp) could be "1+(2*3)".
The reified type of a concrete syntax definition does contain information about the productions, but I am not sure if this approach is better than a dedicated data structure. Any pointers of how could I implement it?
The most natural thing is to use the Tree data-type from the ParseTree module in the standard library. It is the format that the parser produces, but you can also use it yourself. To get a string from the tree, simply print it in a string like so:
str s = "<myTree>";
A relatively complete random tree generator can be found here: https://github.com/cwi-swat/drambiguity/blob/master/src/GenerateTrees.rsc
The core of the implementation is this:
Tree randomChar(range(int min, int max)) = char(arbInt(max + 1 - min) + min);
Tree randomTree(type[Tree] gr)
= randomTree(gr.symbol, 0, toMap({ <s, p> | s <- gr.definitions, /Production p:prod(_,_,_) <- gr.definitions[s]}));
Tree randomTree(\char-class(list[CharRange] ranges), int rec, map[Symbol, set[Production]] _)
= randomChar(ranges[arbInt(size(ranges))]);
default Tree randomTree(Symbol sort, int rec, map[Symbol, set[Production]] gr) {
p = randomAlt(sort, gr[sort], rec);
return appl(p, [randomTree(delabel(s), rec + 1, gr) | s <- p.symbols]);
}
default Production randomAlt(Symbol sort, set[Production] alts, int rec) {
int w(Production p) = rec > 100 ? p.weight * p.weight : p.weight;
int total(set[Production] ps) = (1 | it + w(p) | Production p <- ps);
r = arbInt(total(alts));
count = 0;
for (Production p <- alts) {
count += w(p);
if (count >= r) {
return p;
}
}
throw "could not select a production for <sort> from <alts>";
}
Tree randomChar(range(int min, int max)) = char(arbInt(max + 1 - min) + min);
It is a simple recursive function which randomly selects productions from a reified grammar.
The trick towards termination lies in the weight of each rule. This is computed a priori, such that every rule has its own weight in the random selection. We take care to give the set of rules that lead to termination at least 50% chance of being selected (as opposed to the recursive rules) (code here: https://github.com/cwi-swat/drambiguity/blob/master/src/Termination.rsc)
Grammar terminationWeights(Grammar g) {
deps = dependencies(g.rules);
weights = ();
recProds = {p | /p:prod(s,[*_,t,*_],_) := g, <delabel(t), delabel(s)> in deps};
for (nt <- g.rules) {
prods = {p | /p:prod(_,_,_) := g.rules[nt]};
count = size(prods);
recCount = size(prods & recProds);
notRecCount = size(prods - recProds);
// at least 50% of the weight should go to non-recursive rules if they exist
notRecWeight = notRecCount != 0 ? (count * 10) / (2 * notRecCount) : 0;
recWeight = recCount != 0 ? (count * 10) / (2 * recCount) : 0;
weights += (p : p in recProds ? recWeight : notRecWeight | p <- prods);
}
return visit (g) {
case p:prod(_, _, _) => p[weight=weights[p]]
}
}
#memo
rel[Symbol,Symbol] dependencies(map[Symbol, Production] gr)
= {<delabel(from),delabel(to)> | /prod(Symbol from,[_*,Symbol to,_*],_) := gr}+;
Note that this randomTree algorithm will not terminate on grammars that are not "productive" (i.e. they have only a rule like syntax E = E;
Also it can generate trees that are filtered by disambiguation rules. So you can check this by running the parser on a generated string and check for parse errors. Also it can generated ambiguous strings.
By the way, this code was inspired by the PhD thesis of Naveneetha Vasudevan of King's College, London.

Multi independent input timer

Imagine that we have independent boolean variables that can occur independently. Now, if at least one of the variables occurs for a certain period of time, an alert will be activated. The common solution is that we use a timer for each variable.
Is there an optimal solution that can only be used with a single timer?
Example for 2 variables with 1 second as passed time:
VAR
Timer1,Timer2:TON;
bVar1,bVar2:BOOL;
tSetDelay:TIME:=T#1S;
Alarm:BOOL;
END_VAR
Timer1(IN:=bVar1,PT:=tSetDelay);
Timer2(IN:=bVar2,PT:=tSetDelay);
IF Timer1.Q RO Timer2.Q THEN
Alarm:=TRUE;
END_IF
If we use OR it won't be true
Timer(IN:=bVar1 OR bVar2,PT:=tSetDelay);
cause the vars may have overlap in the same tSetDelay time, it means that they may happen less than the delay, but the timer output be true.
In this example, we have only 2 variables, but if we have many more variables it will be more important to find a better solution.
It it not possible to manage this with a single timer.
Given the that you want to ensure that the triggering source is a single variable (without any logical interference from additional variables), each variable must be compared against it own history (timer).
Recommended path forward would be to build an Alarm function block that handles the majority of the logic here in a consistent manner. An example of this kind of function block is below:
fb_AlarmMonitor
VAR_INPUT
monitor : ARRAY [ 0..7 ] OF POINTER TO BOOL;
duration : TIME;
END_VAR
VAR_OUTPUT
alarm : BOOL;
END_VAR
VAR
timers : ARRAY [ 0..7 ] OF TON;
END_VAR
VAR_TEMP
i : UDINT;
END_VAR
alarm := false;
FOR i := 0 TO 7 BY 1 DO
// Only run process if linked boolean
IF monitor[ i ] <> 0 THEN
timers[ i ]( in := monitor[ i ]^,
pt := duration );
alarm := timers[ i ].Q OR alarm;
END_IF
END_FOR
Implementation
VAR
// Alarm flags
flag_1, flag_2, flag_3
: BOOL;
// Pointers to alarm flags
flag_array : ARRAY [ 0..7 ] OF POINTER TO BOOL
:=[ ADR( flag_1 ),
ADR( flag_2 ),
ADR( flag_3 ) ];
// Monitoring flags
monitor : fb_AlarmMonitor
:=( monitor := flag_array,
duration := T#10S );
END_VAR
monitor();
You cannot do this without individual timers. Here is how I would approach this.
Set global constant and variables
VAR_GLOBAL
glbEvents: ARRAY[1..c_EventsNum] OF stMyEvents; (* Events array *)
END_VAR
VAR_GLOBAL CONSTANT
c_EventsNum: INT := 3; (* Number of events *)
END_VAR
Now you can map glbEvents[1].State to inputs of PLC
Define new structure
TYPE stMyEvents : STRUCT
State : BOOL; (* Event current state *)
StateM : BOOL; (* Memmory of state in previouse cycle to get the trigger *)
Timer: TON := (PT := T#1S); (* Timer *)
END_STRUCT
END_TYPE
Create function
FUNCTION ProcessEvents : BOOL
VAR
iCount: INT; (* Counter *)
END_VAR
FOR iCount := 1 TO c_EventsNum DO
glbEvents[iCount].Timer(IN := glbEvents[iCount].State);
IF glbEvents[iCount].Timer.Q THEN
ProcessEvents := TRUE;
EXIT;
END_IF;
END_FOR;
END_FUNCTION
Implementation
PROGRAM PLC_PRG
VAR
xAlarm: BOOL; (* Alarm *)
END_VAR
IF ProcessEvents() THEN
// Alarm happened
END_IF;
END_PROGRAM
With this approach although you do not have 1 Timer, you have certain level of abstraction that makes it more flexible to support and modify.
But if you absolutely do not want to have so many TON timers, you can create your own timer. It will be single timer in one FB
VAR_GLOBAL
glbEvents: ARRAY[1..c_EventsNum] OF stMyEvents; (* Events array *)
END_VAR
VAR_GLOBAL CONSTANT
c_EventsNum: INT := 3; (* Number of events *)
END_VAR
TYPE stMyEvents : STRUCT
State : BOOL; (* Event current state *)
StateM : BOOL; (* Memmory of state in previouse cycle to get the trigger *)
TimeM: TIME; (* Memmory of event start time *)
END_STRUCT
END_TYPE
FUNCTION_BLOCK ProcessEvents
VAR
iCount: INT; (* Counter *)
END_VAR
VAR_OUTPUT
Q: BOOL; (* Impulse if alarm *)
END_VAR
Q := FALSE;
FOR iCount := 1 TO c_EventsNum DO
(* Get raising edge and save the timer *)
IF glbEvents[iCount].State AND NOT glbEvents[iCount].StateM THEN
glbEvents[iCount].TimeM := TIME();
END_IF;
glbEvents[iCount].StateM := glbEvents[iCount].State;
(* If event is low reset timer *)
IF NOT glbEvents[iCount].State THEN
glbEvents[iCount].TimeM := T#0S;
END_IF;
(* if more than a second make impuls on Q *)
IF (glbEvents[iCount].TimeM > T#0S) AND ((TIME() - glbEvents[iCount].TimeM) >= T#1S) THEN
Q := TRUE;
glbEvents[iCount].TimeM := T#0S;
END_IF;
END_FOR;
END_FUNCTION_BLOCK
PROGRAM PLC_PRG
VAR
fbeventProcess: ProcessEvents; (* function block *)
END_VAR
fbeventProcess();
IF fbeventProcess.Q THEN
// Alarm happened
END_IF;
END_PROGRAM

parsing text with Parse::RecDescent

I am trying to parse some text with Parse::RecDescent
from :
x=2 and y=2 and f=3 and (x has 3,4 or r=5 or r=6 ) and z=2
to something like :
x equal 2 and y equal 2 and f equal 3 and (( x contains 3 or x contains 4 or r equal 5 or requal 6 )) and z equal 2
other example :
input :
x= 3 and y has 5 and (z has 6 or z=3 ) and f=2
output :
x equals 3 and (( y contains 5)) and ((z has 6 or z equals 3)) and f equals 2
my question if i find a list of those operators :
has ,or
i should put "((" before the code and "))" after the code as mentioned on the example aboves
is it possible to do something like this with Parse::RecDescent ?
The grammar would look something like the following:
parse : expr EOF
expr : logic_or
# vvv Lowest precedence vvv
logic_or : <leftop: logic_and LOGIC_OR logic_and>
logic_and : <leftop: comparison LOGIC_AND comparison>
comparison : term comparison_[ $item[1] ]
comparison_ : '=' term
| HAS ident_list
|
# ^^^ Highest precedence ^^^
ident_list : <leftop: IDENT ',' IDENT>
term : '(' expr ')'
| IDENT
# Tokens
IDENT : /\w+/
LOGIC_OR : /or\b/
LOGIC_AND : /and\b/
HAS : /has\b/
EOF : /\Z/
Now you just need to add the code block to emit the desired output.
In comparison_, the LHS term is available as $arg[0].
I had to make some assumptions, so there could be errors.

Printing symbol name and value in Mathematica

I'd like to create a function My`Print[args__] that prints the names of the symbols that I pass it, along with their values. The problem is that before the symbols are passed to My`Print, they're evaluated. So My`Print never gets to see the symbol names.
One solution is to surround every argument that I pass to My`Print with Unevaluated[], but this seems messy. Is there a way of defining a MACRO such that when I type My`Print[args__], the Mathematica Kernel sees My`Print[Unevaluated /# args__]?
You need to set the attribute HoldAll on your function, with SetAttribute[my`print].
Here's a possible implementation:
Clear[my`print]
SetAttributes[my`print, HoldAll]
my`print[args__] :=
Scan[
Function[x, Print[Unevaluated[x], " = ", x], {HoldAll}],
Hold[args]
]
I used lowercase names to avoid conflicts with built-ins or functions from packages.
EDIT:
Just to make it explicit: I have two functions here. One will print the value of a single symbol, and is implemented as a Function inside. You can just use this on its own if it's sufficient. The other is the actual my`print function. Note that both need to have the HoldAll attribute.
ClearAll[My`Print]
SetAttributes[My`Print, HoldAll]
My`Print[args___] :=
Do[
Print[
Extract[Hold[args], i, HoldForm], "=", List[args][[i]]
], {i, Length[List[args]]}
]
ape = 20;
nut := 20 ape;
mouse = cat + nut;
My`Print[ape, nut, mouse]
(* ==>
ape=20
nut=400
mouse=400+cat
*)
SetAttributes[MyPrint, HoldAll];
MyPrint[var_] :=
Module[
{varname = ToString[Hold[var]]},
Print[StringTake[varname, {6, StringLength[varname] - 1}],
" = ", Evaluate[var]]
]
Coming late to the party - one can use Listability to get a rather elegant (IMO) solution avoiding explicit loops or evaluation control constructs:
ClearAll[prn];
SetAttributes[prn, {HoldAll, Listable}];
prn[arg_] := Print[HoldForm[arg], " = ", arg];
prn[args___] := prn[{args}]
Stealing the test case from #Sjoerd,
In[21]:= prn[ape,nut,mouse]
During evaluation of In[21]:= ape = 20
During evaluation of In[21]:= nut = 400
During evaluation of In[21]:= mouse = 400+cat
Out[21]= {Null,Null,Null}
Here is another variation of My`Print to add to the mix:
ClearAll[My`Print]
SetAttributes[My`Print, HoldAll]
My`Print[expr_] := Print[HoldForm[expr], " = ", expr]
My`Print[exprs___] := Scan[My`Print, Hold[exprs]]
... and another...
ClearAll[My`Print]
SetAttributes[My`Print, HoldAll]
My`Print[args___] :=
Replace[
Unevaluated # CompoundExpression # args
, a_ :> Print[HoldForm[a], " = ", a]
, {1}
]
Either way, the use is the same:
$x = 23;
f[x_] := 1 + x
My`Print[$x, $x + 1, f[1]]
(* prints:
$x = 23
$x+1 = 24
f[1] = 2
*)
In addition to the other answers consider the functions DownValues, OwnValues and UpValues:
In[1] := f[x_] := x^2
In[2] := f[x_, y_] := (x + y)^2
In[3] := DownValues[f]
Out[3] = {HoldPattern[f[x_]] :> x^2, HoldPattern[f[x_, y_]] :> (x + y)^2}
http://reference.wolfram.com/mathematica/ref/DownValues.html