How to result invalid LogicalExpression in Dafny? - methods

Consider the following dafny function below:
function method unpair(n: nat): (nat, nat)
{
var x,y :| n == (x+y)*(x+y+1)/2 + y;
return (x,y)
}
Given some natural number n, I would like to identify 2 natural numbers x and y which satisfy the equation (x+y)*(x+y+1)/2 + y. This is possible using Cantor's Pairing Function, but not sure I have the correct syntax for it, as dafny is throwing an error: "invalid LogicalExpression" on the return line. How can I resolve this error?

A function method is (perhaps confusingly) a function, with the only difference being that it is allowed to be called from non-ghost contexts. In any function (including function methods), we don't need to say return in Dafny. Instead, the body of the function is just the expression we want to return. So you should write
function method unpair(n: nat): (nat, nat)
{
var x,y :| n == (x+y)*(x+y+1)/2 + y;
(x,y)
}
At this point, you have a syntactically valid function.
Dafny then complains about several semantic issues. First, there are a few errors about "not satisfying the constraints of type nat". You can fix those by explicitly declaring x and y to have type nat, like this:
function method unpair(n: nat): (nat, nat)
{
var x:nat,y:nat :| n == (x+y)*(x+y+1)/2 + y;
(x,y)
}
At this point, Dafny reports one additional error, which is that it cannot prove that there always exist such an x and y. This is a more fundamental problem. You will need to convince Dafny (probably using a separate lemma) that such numbers always exist.

Related

How to overload arithmetic operators (+, *, -, /) for functions in c++?

I would like to implement a numerical integral whose integrand is evaluated at quadrature points. Therefore something like: integral(domain, f), where domain is indeed the domain where I want to integrate and f is the function to integrate. f is only a function of the Point p (quadrature points) inside the domain and can have vector values (scalar is a particular case).
Since the function f can be, in general, a combination of different functions, I wonder how to overload arithmetic operators for functions.
I already found this Implementing multiplication operator for mathematical functions C++
but it does not cover my question, because the Function returns only x, while In my case I would like to have different Functions which can return a more complex function of x.
So, let f_1,...f_N be different functions which have the same return type, for example a std::array<double,M> with given length M, and which receive the same input Point p, i.e for I=1,...,N:
std::array<double,M> f_i(Point p)
{ std::array<double,M> x;
\\ compute x somehow depending on i
return x;}
Then I would like to create f as a combination of the previous f_1,...f_N, e.g. f=f_1 *f_2+(f_3*f_4)*f_5... (here the operations are meant to be component wise).
In this way I could evaluate f(p) inside integral(domain, f), obtaining for each quadrature point exactly:
f_1(p) *f_2(p)+(f_3(p)*f_4(p))*f_5(p)...
Edit:
I know I have to use functors and not simple functions (which I used just to state the problem), but I am not able to figure out how for this purpose.
Any hint?
Thank you

How can I emulate the results of this if then then statement while using correct syntax?

Working on an exercise for university class and cant seem to represent what I am trying to do with correct syntax in ocaml. I want the function sum_positive to sum all the positive integers in the list into a single int value and return that value.
let int x = 0 in
let rec sum_positive (ls: int list) = function
|h::[] -> x (*sum of positive ints in list*)
|[] -> 0
|h::t -> if (h >= 0) then x + h then sum_positive t else sum_positive t (*trying to ensure that sum_positive t will still run after the addition of x + h*)
On compiling I am met with this error,
File "functions.ml", line 26, characters 34-38:
Error: Syntax error
This points to the then then statement I have in there, I know it cannot work but I cant think of any other representations that would.
You have if ... then ... then which is not syntactically valid.
It seems what you're asking is how to write what you have in mind in a way that is syntactically valid. But it's not clear what you have in mind.
You can evaluate two expressions in OCaml sequentially (one after the other) by separating them with ;. Possibly that is what you have in mind.
However it seems to me your code has bigger problems than just syntax. It appears you're trying to use x as an accumulated sum for the calculation. You should be aware that OCaml variables like x are immutable. Once you say let x = 0, the value can't be changed later. x will always be 0. The expression x + h doesn't change the value of x. It just evaluates to a new value.
The usual way to make this work is to pass x as a function parameter.
I was getting an issue that had involved the parameter of , I believe it was because I was trying to add an int value to function of type int list. This is what I ended up with.
let rec sum_positive = function
|[] -> 0
|h::t -> if h > 0 then h + (sum_positive t) else sum_positive t
a lot simpler than I thought it out to be.

Differentiate an infix formal language functions

I have a source file like (without loss of generality (only to image a possible syntax)):
function a()
return g // global variable without any internal structure exactly
end
function b(x, y)
local z = x * y
return z + 1
end
function c(z, t)
return b(z * z, a())
end
// ...etc
I want to defferentiate any function WRT to some variable.
All the formal parametres we can treat as a functions with unknown at derive time internal structure.
If I stand correct further, then the following is truth (for depending symbols ' is part of symbol, for global variables is operator during substitute time stage (def: g{g} is one, but g{y} is zero)):
function a'()
return g';
end
function b'(x, y, x', y')
local z' = x' * y + x * y'
return z' + 0
end
But what to do with last function? Namely, with actual parameters in substitution of function b?
Is there any ready to use implementations of general algorithm to work with the above? What to do with higher order derivatives (especially interesting, how to handle the formal parameters)? Are there any other possible unclear cases?
I would suggest having your parameters be symbolic expressions that know how to respond to derivatives, and having all operations take functions and return functions. Then you will get a final expression that knows how to be represented as a derivative. Furthermore you can do things like partial derivatives at a later point because you have the symbolic expression.
For a real example of what I mean, see http://www.elem.com/~btilly/kelly-criterion/js/advanced-math.js for a library that I wrote to solve a calculus problem in JavaScript, and search for "Optimize if requested" in the source for http://www.elem.com/~btilly/kelly-criterion/betting-returns2.html to see how I used it. See http://www.elem.com/~btilly/kelly-criterion/ for an explanation of why I was writing that code.
In that example I, of course, was not working from infix notation. But that is a standard parsing problem that I think you know how to solve.

Evaluating three-variable expression in Prolog

Follow the Four-Step Abstract design process to define recursive rules to compute mathematical functions. You must indicate (use comments to code) which step is used. Note, a Prolog rule does not return a value. You need to use a parameter to hold the return value. You may NOT use the exponential operator ** to compute the expressions.
Write a recursive rules factbar(F, X, Y, N) to compute F = ((2*X + Y)^N)! (factorial of expbar). The rule must call (use) the rule expbar that you designed..
Now for doing this operation F = ((2*X + Y)^N) I have already written my code but I do not know how to write factorial in Prolog:
expbar(R, X, Y, N) :-
X > 0, Y > 0, N > 0,
R is (2 * X + Y) ** N.
Although I have used ** in my program for exponent I did not know how to use the other way.
I have no idea what the "four step abstract design process" is and you haven't included that detail. As a result, you're going to instead get my two-step recursive function design process. Your predicate is right except you haven't defined pow/3, a function to compute powers. This is obviously the crux of your assignment. Let's do it.
Step one: identify your base cases. With arithmetic functions, the base case involves the arithmetic identity. For exponentiation, the identity is 1. In other words, X**1 = X. Write this down:
pow(X,1,X).
Because this is a function with two inputs and one result, we'll encode it as an arity-3 predicate. This fact simply says X to the 1st power is X.
Step two. Now consider the inductive case. If I have X**N, I can expand it to X * (X**(N-1)). By the definition of exponentiation and the induction rule, this completes the definition of the predicate. Encode it in Prolog syntax:
pow(X,N,Y) :-
N > 1,
succ(N0, N),
pow(X, N0, Y0),
Y is X * Y0, !.
This gives you a predicate for calculating exponents. If you replace your use of **/2 in your expbar/4 predicate, you fulfill the requirements of your assignment.

What's the formal term for a function that can be written in terms of `fold`?

I use the LINQ Aggregate operator quite often. Essentially, it lets you "accumulate" a function over a sequence by repeatedly applying the function on the last computed value of the function and the next element of the sequence.
For example:
int[] numbers = ...
int result = numbers.Aggregate(0, (result, next) => result + next * next);
will compute the sum of the squares of the elements of an array.
After some googling, I discovered that the general term for this in functional programming is "fold". This got me curious about functions that could be written as folds. In other words, the f in f = fold op.
I think that a function that can be computed with this operator only needs to satisfy (please correct me if I am wrong):
f(x1, x2, ..., xn) = f(f(x1, x2, ..., xn-1), xn)
This property seems common enough to deserve a special name. Is there one?
An Iterated binary operation may be what you are looking for.
You would also need to add some stopping conditions like
f(x) = something
f(x1,x2) = something2
They define a binary operation f and another function F in the link I provided to handle what happens when you get down to f(x1,x2).
To clarify the question: 'sum of squares' is a special function because it has the property that it can be expressed in terms of the fold functional plus a lambda, ie
sumSq = fold ((result, next) => result + next * next) 0
Which functions f have this property, where dom f = { A tuples }, ran f :: B?
Clearly, due to the mechanics of fold, the statement that f is foldable is the assertion that there exists an h :: A * B -> B such that for any n > 0, x1, ..., xn in A, f ((x1,...xn)) = h (xn, f ((x1,...,xn-1))).
The assertion that the h exists says almost the same thing as your condition that
f((x1, x2, ..., xn)) = f((f((x1, x2, ..., xn-1)), xn)) (*)
so you were very nearly correct; the difference is that you are requiring A=B which is a bit more restrictive than being a general fold-expressible function. More problematically though, fold in general also takes a starting value a, which is set to a = f nil. The main reason your formulation (*) is wrong is that it assumes that h is whatever f does on pair lists, but that is only true when h(x, a) = a. That is, in your example of sum of squares, the starting value you gave to Accumulate was 0, which is a does-nothing when you add it, but there are fold-expressible functions where the starting value does something, in which case we have a fold-expressible function which does not satisfy (*).
For example, take this fold-expressible function lengthPlusOne:
lengthPlusOne = fold ((result, next) => result + 1) 1
f (1) = 2, but f(f(), 1) = f(1, 1) = 3.
Finally, let's give an example of a functions on lists not expressible in terms of fold. Suppose we had a black box function and tested it on these inputs:
f (1) = 1
f (1, 1) = 1 (1)
f (2, 1) = 1
f (1, 2, 1) = 2 (2)
Such a function on tuples (=finite lists) obviously exists (we can just define it to have those outputs above and be zero on any other lists). Yet, it is not foldable because (1) implies h(1,1)=1, while (2) implies h(1,1)=2.
I don't know if there is other terminology than just saying 'a function expressible as a fold'. Perhaps a (left/right) context-free list function would be a good way of describing it?
In functional programming, fold is used to aggregate results on collections like list, array, sequence... Your formulation of fold is incorrect, which leads to confusion. A correct formulation could be:
fold f e [x1, x2, x3,..., xn] = f((...f(f(f(e, x1),x2),x3)...), xn)
The requirement for f is actually very loose. Lets say the type of elements is T and type of e is U. So function f indeed takes two arguments, the first one of type U and the second one of type T, and returns a value of type U (because this value will be supplied as the first argument of function f again). In short, we have an "accumulate" function with a signature f: U * T -> U. Due to this reason, I don't think there is a formal term for these kinds of function.
In your example, e = 0, T = int, U = int and your lambda function (result, next) => result + next * next has a signaturef: int * int -> int, which satisfies the condition of "foldable" functions.
In case you want to know, another variant of fold is foldBack, which accumulates results with the reverse order from xn to x1:
foldBack f [x1, x2,..., xn] e = f(x1,f(x2,...,f(n,e)...))
There are interesting cases with commutative functions, which satisfy f(x, y) = f(x, y), when fold and foldBack return the same result. About fold itself, it is a specific instance of catamorphism in category theory. You can read more about catamorphism here.

Resources