How to use TLA+ to define sequential actions? - function

Say I have a simple set of sequential actions (which I will first define imperatively):
start(a, 1)
move(a, 3)
move(a, 5)
move(a, 4)
move(a, 2)
That is, we have a game piece a and start it at position 1. Then we move it sequentially first to 3, then to 5, then 4, then 2. Once per step.
How would you define this using TLA+? Trying to wrap my mind around how to specify complicated imperative action sequences in TLA+.

The behaviours sketched in the question could be described in TLA+ as follows:
---- MODULE Steps ----
VARIABLE a
Init == a = 1
Next == \/ /\ a = 1
/\ a' = 3
\/ /\ a = 3
/\ a' = 5
\/ /\ a = 5
/\ a' = 4
\/ /\ a = 4
/\ a' = 2
Spec == Init /\ [][Next]_a /\ WF_a(Next)
=====================
The behavior of variable a is specified by the temporal formula Spec (other variables can behave in arbitrary ways).
The variable a starts equal to 1 (by the conjunct Init), and a temporal step either leaves a unchanged, or it changes it from 1 to 3. If this change occurs, then the following temporal steps either leave a unchanged, or change it from 3 to 5. The changes of value to a may continue until a equals 2. Further changes to a are impossible. Once a becomes equal to 2, it remains forever equal 2. These are the possible changes of a, as specified by the conjunct [][Next]_a, which means [](Next \/ UNCHANGED a), i.e., [](Next \/ (a' = a)), with the symbol [] meaning "always".
The conjuncts Init and [][Next]_a specify a safety property. Safety is about what can happen, not what must happen. Liveness (what must happen) is specified with the conjunct WF_a(Next), which describes weak fairness. The formula WF_a(Next) requires that if a step that satisfies the formula Next and changes the value of variable a is enabled uninterruptedly, then such a step must eventually occur.
In other words, if it is possible to change variable a by taking a step that satisfies Next (a <<Next>>_a-step), then a cannot remain forever unchanged, but must eventually change in a way that is described by Next. Indeed, while a is not 2, but 1, 3, 5, or 4, action <<Next>>_a (which means Next /\ (a' # a), i.e., Next and a changes value) is enabled, so a will keep changing until it reaches the value 2. When a is 2, <<Next>>_a becomes disabled.

There are a large number of ways to do this, but here are two simple solutions which spring to mind; the first uses a macro:
---- MODULE Steps ----
VARIABLE a
move(start, end) ==
/\ a = start
/\ a' = end
Init ==
/\ a = 1
Next ==
\/ move(1, 3)
\/ move(3, 5)
\/ move(5, 4)
\/ move(4, 2)
Spec ==
/\ Init
/\ [][Next]_a
=====================
Note the above will only work as long as your sequence of moves doesn't return to the same state. If it does, you'll have to add something like a pc "program counter" variable and a sequence and yada yada yada... at that point you're probably better off using PlusCal, a TLA+ variant which often works better for writing sequential actions:
---- MODULE Steps ----
(* --algorithm Steps
variables a = 1;
begin
a := 3;
a := 5;
a := 4;
a := 2;
end algorithm; *)
=====================
This has to be translated into TLA+ before it can be run by TLC. Use
CTRL+T in the TLA+ toolbox
Parse module command in the VS Code extension
java pcal.trans Steps.tla with the CLI

Related

Assistance working with Binary Trees in SML

I'm new to SML and would like some assistance in using the following implementation of a binary tree.
datatype tree = NODE of int * tree * tree | LEAF of int;
I see that the tree is defined by either nodes which has two sub-trees or a LEAF with an integer.
How can I access the subtrees so that I can determine the maximum , the minimum, and if the element is present in the tree?
What is the process of accessing either the left and right sub-trees?
What is the process of accessing either the left and right sub-trees?
You use pattern matching:
fun goLeft (NODE (_, l, _)) = l
| goLeft LEAF = raise Fail "Cannot go left here!"
fun goRight (NODE (_, _, r)) = r
| goRight LEAF = raise Fail "Cannot go right here!"
How can I [...] determine the maximum, the minimum, and if the element is present in the tree?
You build recursive functions that pattern match on sub-trees.
For example, there is no invariant in a binary tree that says that the minimal element has a fixed, known location in the tree. But this invariant is present in a binary search tree, in which all elements in every left sub-tree (including the root) are made sure to be less than or equal to all the elements of their right sub-trees.
The tree
5
/ \
3 8
/ / \
2 7 9
qualifies as a binary search tree because this invariant holds.
Finding the minimal element in such a tree means recursing in such a way that you always pick the left sub-tree until there is no left sub-tree, in which case you have found the minimum. How do you know when to stop recursion?
fun goLeeeft (NODE (_, l, _)) = goLeeeft l
| goLeeeft LEAF = "I've gone all the way left, but I have nothing to show for it."
fun minimum (NODE (x, l, r)) = (* is this the last non-leaf node? *)
| minimum LEAF = raise Empty (* whoops, we recursed too far! *)
When you pattern match one level deep, that is, on NODE (x, l, r), you only know that this is a non-leaf node, but you don't know the exact value located in the node, x, and you don't know anything about the sub-structure of this node's left and right sub-trees.
You could go two ways here: Either make a helper function that tells you when to stop recursing, or pattern match one level deeper into l. Here are two examples of that; they perform the same thing:
(* Using a helper function *)
fun isLeaf (NODE (_, _, _)) = false
| isLeaf LEAF = true
fun minimum (NODE (x, l, _)) =
if isLeaf l
then x
else minimum l
| minimum LEAF = raise Empty
(* Using direct pattern matching *)
fun minimum (NODE (x, LEAF, _)) = x
| minimum (NODE (x, l, _)) = minimum l
| minimum LEAF = raise Empty
Now maximum writes itself.
As a curiosity, you can define generic recursion schemes such as folding on trees: Sml folding a tree

How does one insert fortran code from an external file into a separate code?

I'd like to have my code take code written in another document, read it, and then use it as though it was written in the code. Say we have the following:
MODULE samplemod
CONTAINS
FUNCTION sillysum(boudary,function) RESULT(counter)
IMPLICIT NONE
REAL(KIND=8) :: boundary, counter
REAL(KIND=8), DIMENSION(:) :: function
INTEGER :: m
counter = 0.d0
DO m = 1, my_mesh%me
counter = function(m) + externalfunction
END DO
END FUNCTION sillysum
END MODULE samplemod
PROGRAM sampleprogram
USE samplemod
REAL(KIND=8), DIMENSION(:) :: function1
ALLOCATE(function1(100))
DO m=1, 100
function1(i) = i
END DO
WRITE(*,*) sillysum(100,function1)
END PROGRAM sampleprogram
Where in some external file (say 'externfunct.txt') one has written m**2. How can the Fortran code read the external function m**2, SIN(m), or even 0 and have that replace externalfunction. Here's a simpler example:
REAL(KIND=8) :: x = 2
CHARACTER(LEN=*) :: strng = "external"
WRITE(*,*) "Hello world, 2 + ", strng, " = ", 2 + external
Where in a txt file I have written I have written SIN(x).
I think there are two different approaches for this (* in fact, there seems a "third" approach also, see EDIT); one is to use a shared library, and the other is to use a parser for math expressions. The first approach is described in a Rossetastone page (Call a function in a shared library) and an SO page (Fortran dynamic libraries, load at runtime?), for example. For the second approach, you can find 3rd-party libraries by searching with "math parser" or "Fortran math parser" etc. Here, I have tried this one because it seems pretty simple (only one module and no installation). If we write a simple test program like this
program test
use interpreter, only: init, evaluate, dp => realkind
implicit none
integer, parameter :: mxvars = 10 !! consider 10 variables at most here
character(10) :: symbols( mxvars )
real(dp) :: values( mxvars ), answer
character(1000) :: funcstr !! a user-defined math expression
character(5) :: stat
!> Define variable names.
symbols( 1 ) = "x"
symbols( 2 ) = "a"
symbols( 3 ) = "b"
symbols( 4 ) = "c"
symbols( 5 ) = "foo"
!> Get a math expression.
print *, "Please input a math expression:"
read(*, "(a)") funcstr !! e.g., a * x + b
!> Init the evaluator.
call init( funcstr, symbols, stat )
if ( stat /= "ok" ) stop "stat /= ok"
!> Set values for the variables.
values( : ) = 0
values( 1 ) = 2.0_dp ! x
values( 2 ) = 10.0_dp ! a
values( 3 ) = 7.0_dp ! b
!> Evaluate.
answer = evaluate( values )
print *, "function value = ", answer
end program
and compile it as (*1)
$ gfortran -ffree-line-length-none interpreter.f90 mytest.f90
we can test various expressions as follows:
$ ./a.out
Please input a math expression:
a * x + b
function value = 27.000000000000000
$ ./a.out
Please input a math expression:
sin( a * x ) + cos( b ) + foo
function value = 1.6668475050709324
The usage of other libraries also seems very similar. Because the performance of each library may be rather different, it may be useful to try several different libraries for comparison.
(*1) The module has some lines with sind, cosd, and tand, but they are not supported by gfortran. So, to compile, I have commented them out and replaced them by stop, i.e.,
stop "sind not supported..."
! pdata(st) = sind(pdata(st))
(I guess sind(x) means sin( x * pi / 180 ), so it may be OK to define it as such.)
[EDIT]
A "third" approach may be to call the built-in eval() function in interpreted languages like Python or Julia via system(), e.g., this SO page. Although this also has a lot of weak points (and it is probably much easier to use such languages directly), calling eval() from Fortran might be useful for some specific purposes.

Is it possible to use functions in Haskell parameters?

I have seen a few examples of Haskell code that use functions in parameters, but I can never get it to work for me.
example:
-- Compute the nth number of the Fibonacci Sequence
fib 0 = 1
fib 1 = 1
fib (n + 2) = fib (n + 1) + fib n
When I try this, it I get this error:
Parse error in pattern: n + 2
Is this just a bad example? Or do I have to do something special to make this work?
What you have seen is a special type of pattern matching called "n+k pattern", which was removed from Haskell 2010. See What are "n+k patterns" and why are they banned from Haskell 2010? and http://hackage.haskell.org/trac/haskell-prime/wiki/RemoveNPlusK
As Thomas mentioned, you can use View Patterns to accomplish this:
{-# LANGUAGE ViewPatterns #-}
fib 0 = 1
fib 1 = 1
fib ((subtract 2) -> n) = fib (n + 1) + fib n
Due to the ambiguity of - in this case, you'll need to use the subtract function instead.
I'll try to help out, being a total newbie in Haskell.
I believe that the problem is that you can't match (n + 2).
From a logical viewpoint, any argument "n" will never match "n+2", so your third rule would never be selected for evaluation.
You can either rewrite it, like Michael said, to:
fib n = fib (n - 1) + fib (n - 2)
or define the whole fibonnaci in a function using guards, something like:
fibonacci :: Integer -> Integer
fibonacci n
| n == 0 = 0
| (n == 1 || n == 2) = 1
| otherwise = fibonacci(n-1) + fibonacci(n-2)
The pattern matcher is limited to constructor functions. So while you can match the arguments of functions like (:) (the list constrcutor) or Left and Right (constructors of Either), you can't match arithmetic expressions.
I think the fib (n+2) = ... notation doesn't work and is a syntax error. You can use "regular expression" style matching for paramters, like lists or tuples:
foo (x:xs) = ...
where x is the head of the list and xs the remainder of the list or
foo (x:[]) =
which is matched if the list only has one element left and that is stored in x. Even complex matches like
foo ((n,(x:xs)):rg) = ...
are possible. Function definitions in haskell is a complex theme and there are a lot of different styles which can be used.
Another possibility is the use of a "switch-case" scheme:
foo f x | (f x) = [x]
foo _ _ = []
In this case, the element "x" is wrapped in a list if the condition (f x) is true. In the other cases, the f and x parameters aren't interesting and an empty list is returned.
To fix your problem, I don't think any of these are applicable, but why don't throw in a catch-remaining-parameter-values function definition, like:
fib n = (fib (n - 1)) + (fib (n - 2))
Hope this helps,
Oliver
Since (+) is a function, you can't pattern match against it. To do what you wanted, you'd need to modify the third line to read: fib n = fib (n - 1) + fib (n - 2).

R: specifying a string as an argument of a function that calls another function

This is a question regarding coding in R.
The example I provide is didactic. Suppose I have functions called 'func1' and 'func2', where each takes two arguments (let's say scalars). I want to specify another function 'applyfunction' that has three args: the last number of the function to use ('1' or '2'), and the two arguments for the function. For example, I want to do something like this (which of course doesn't work):
applyfunction(1,2,3) where it would effectively run func1(2,3) and
applyfunction(2,9,43) where it would effectively run func2(9,43).
Any ideas?
Best, DB
You might want to look at do.call(), which calls a function with arguments supplied in a list. It is not to hard to write a wrapper around this that does exactly what you want.
function1=function(a,b)a+b
function2=function(a,b,c)a+b+c
do.call("function1",list(1,2))
do.call("function2",list(1,2,3))
EDIT: A wrapper would be:
applyfunction=function(fun,...)do.call(fun,list(...))
applyfunction("function1",1,2)
applyfunction("function2",1,2,3)
Here's another alternative. You can add more functions to the switch list.
func1 <- function(a, b) a + b
func2 <- function(a, b) a - b
applyfunction <- function(FUN, arg1, arg2) {
appFun <- switch(FUN,
func1, # FUN == 1
func2, # FUN == 2
stop("function ", FUN, " not defined")) # default
appFun(arg1, arg2)
}
applyfunction(1,2,3)
# [1] 5
applyfunction(2,9,43)
# [1] -34
applyfunction(3,9,43)
# Error in applyfunction(3, 9, 43) : function 3 not defined
If you really want it done 'by the numbers':
> applyfunction=function(n,a,b){get(paste("func",n,sep=""))(a,b)}
> func1=function(a,b){a+b}
> func2=function(a,b){a*b}
> applyfunction(1,4,3)
[1] 7
> applyfunction(2,4,3)
[1] 12
Uses get and paste to get the function associated with a name.
What about using one of the functions variables as a switch?
func1 <- function(x,y,z) {
## Function One stuff goes here
if (x == 1) {
var1 <- 1
}
## Function Two stuff goes here
if (x == 2) {
var1 <- 2
}
return(var1)
}
And, you get to use the same function, with the switch being the variable "x":
> func1(1,1,1)
[1] 1
> func1(2,1,1)
[1] 2
Here an alternate to switch or paste, just use indexing to select from a list:
function1=function(a,b) a+b
function2=function(a,b,c) a*b
applyfunc <- function(n, aa, bb){ c(function1, function2)[[n]](aa,bb) }
applyfunc(1, 4, 3)
# [1] 7
applyfunc(2, 4, 3)
#[1] 12
applyfunc(3, 4, 3)
# Error in c(function1, function2)[[n]] : subscript out of bounds

Mixing addition and subtraction with logical NOT

I found some exercises where you combine n-bit 2's complement values in different ways and simplify the output where possible. (Their practice exercises use 16-bit, but that's irrelevant).
Eg:
!(!x&!y) == x|y
0 & y, negate the output == -1
I'm having no problem applying De Morgan's laws with the examples using AND, OR, and NOT but I am having difficulty using NOT with + and -
Eg:
!(!x+y) == x-y
!(y-1) == -y
How does NOT distribute?
Edit: responding to comments: I realize this is a bitwise NOT. My question is: in algebraic terms, how does it distribute as per algebra? Example on Wikipedia
With 2's complement numbers when you bitwise NOT them it is the same as saying the negative of the number minus 1, so !x is equivalent to -x - 1 where x can be a single variable or an expression.
Starting with !(!x+y), well !x is going to be -x - 1 so then it is !(-x - 1 + y) which becomes -(-x - 1 + y) - 1 which simplifies to x - y.
And for !(y-1), that becomes -(y - 1) - 1 = -y + 1 - 1 = -y.