Alloy ternary relation override - alloy

I have a ternary relation in a sig Record, and I have a predicate changeRecord to modify the third element if the first two element are matched. But the ++ override only check the domain (the first element), how can I do that?
sig Account{}
sig Record{
allowance: Account -> Account -> one Int
}
pred changeRecord(a1, a2: Account, r1, r2: Record, val: Int){
val > 0
a1 != a2
r2.allowance = r1.allowance ++ (a1 -> a2 -> val) // ***
}
The *** line currently replaces any tuples starting with a1, with a1 -> a2 -> val, but I want that replacement only happen on lines like a1 -> a2 -> someothervalue.

Here's a first version that overrides only the tuples that match a1->a2 with a1->a2->val'.
It involves several steps and I'm sure more experienced Alloy users can accomplish the same task more succinctly, perhaps along a different line of thinking.
pred changeRecord[a1, a2: Account, r1, r2: Record, val': Int] {
val' > 0
a1 != a2
// step 1.
let val_for_a1_a2_in_r1 = a2.(a1.(r1.allowance)) |
// step 2.
let a1_a2_val_in_r1 = a1->a2->val_for_a1_a2_in_r1 |
// step 3.
let r1_allowance_without_a1_a2_val = r1.allowance - a1_a2_val_in_r1 |
// step 4.
let a1_a2_val' = a1_a2_val_in_r1 ++ a1->a2->val' |
// step 5.
r2.allowance = r1_allowance_without_a1_a2_val + a1_a2_val'
}
The idea is to separate those tuples in r1.allowance that match a1->a2 in steps 1. and 2., subtract them from r1.allowance in step 3., override them by a1->a2->val' in step 4. and finally 'assign' the overridden set plus r1_allowance_without_a1_a2_val to r2.allowance in step 5. Please note that for a certain a1->a2 pair there may be several tuples with different vals in r1.allowance and these all will be overridden by a1->a2->val' and then, of course, only one a1->a2->val' will appear in r2.allowance.
Remark: I haven't checked the correctness of this solution extensively.

Related

Get corresponding element from maximum of element wise 2d array

I have four 2d arrays.
A = [[1,6], [3,5]]
A' = [[11,22], [33,44]] //each index value is related to corresponding index at A
similarly
B = [[5,2],[2,3]]
B' = [[55,66],[77,88]]
output
o/p = [[5,6], [3,5]]
o/p' = [[55,22],[33,44]] // how to get this output
I want to get element wise maximum from A and B, but I want to get the corresponding element
from A' and B'.
Doing a n^2 iteration is taking a lot of time.
numpy.maximum(A,B,A) can get me maximum value but how can I get corresponding elements from A' and B'.
You could do this:
# Defining the arrays
A = np.array([[1,6], [3,5]])
A2 = np.array([[11,22], [33,44]])
B = np.array([[5,2],[2,3]])
B2 = np.array([[55,66],[77,88]])
# Get maximum of A and B. Do not do np.maximum(A, B, A), as this overwrites A.
C = np.maximum(A, B)
# Get indices where C = A and C = B.
A_indices = np.where(C == A)
B_indices = np.where(C == B)
# Get corresponding A2 and B2 values.
C2 = np.copy(C)
C2[A_indices] = A2[A_indices]
C2[B_indices] = B2[B_indices]
C2 now has the values you want. Let me know if you have any questions.

How to build a route from point "A" to point "E" with the condition that the end point is the point "E"?

I need to build all possible routes from point "A" to point "E" with the condition that the end point is a point "B"
Task example:
From : A, To: B
Example result:
A -> E
A -> B -> E
A -> C -> D -> E
A -> B -> C -> D -> E
So far I was able to do so:
FOR v, e, p IN 1..10 OUTBOUND "city/907499" GRAPH 'CityToCity'
FILTER p.edges[*].user ALL == "6609844"
FILTER p.vertices[4]._id == "city/1012911"
RETURN p
But in this example, you must explicitly indicate at what level the endpoint should be located. How to make it simple from A to E without specifying level 4 in this filter "p.vertices [4] ._ id" ???
As the AQL documentation says:
// access last array element
u.friends[-1]
So in your example, specify the constraint on p.vertices[-1]._id
Also specify a very large number for MAX. Unfortunately, currently AQL requires that a specific value be given, but a ridiculously large value can be specified.

Scala String Similarity

I have a Scala code that computes similarity between a set of strings and give all the unique strings.
val filtered = z.reverse.foldLeft((List.empty[String],z.reverse)) {
case ((acc, zt), zz) =>
if (zt.tail.exists(tt => similarity(tt, zz) < threshold)) acc
else zz :: acc, zt.tail
}._1
I'll try to explain what is going on here :
This uses a fold over the reversed input data, starting from the empty String (to accumulate results) and the (reverse of the) remaining input data (to compare against - I labeled it zt for "z-tail").
The fold then cycles through the data, checking each entry against the tail of the remaining data (so it doesn't get compared to itself or any earlier entry)
If there is a match, just the existing accumulator (labelled acc) will be allowed through, otherwise, add the current entry (zz) to the accumulator. This updated accumulator is paired with the tail of the "remaining" Strings (zt.tail), to ensure a reducing set to compare against.
Finally, we end up with a pair of lists: the required remaining Strings, and an empty list (no Strings left to compare against), so we take the first of these as our result.
The problem is like in first iteration, if 1st, 4th and 8th strings are similar, I am getting only the 1st string. Instead of it, I should get a set of (1st,4th,8th), then if 2nd,5th,14th and 21st strings are similar, I should get a set of (2nd,5th,14th,21st).
If I understand you correctly - you want the result to be of type List[List[String]] and not the List[String] you are getting now - where each item is a list of similar Strings (right?).
If so - I can't see a trivial change to your implementation that would achieve this, as the similar values are lost (when you enter the if(true) branch and just return the acc - you skip an item and you'll never "see" it again).
Two possible solutions I can think of:
Based on your idea, but using a 3-Tuple of the form (acc, zt, scanned) as the foldLeft result type, where the added scanned is the list of already-scanned items. This way we can refer back to them when we find an element that doesn't have preceeding similar elements:
val filtered = z.reverse.foldLeft((List.empty[List[String]],z.reverse,List.empty[String])) {
case ((acc, zt, scanned), zz) =>
val hasSimilarPreceeding = zt.tail.exists { tt => similarity(tt, zz) < threshold }
val similarFollowing = scanned.collect { case tt if similarity(tt, zz) < threshold => tt }
(if (hasSimilarPreceeding) acc else (zz :: similarFollowing) :: acc, zt.tail, zz :: scanned)
}._1
A probably-slower but much simpler solution would be to just groupBy the group of similar strings:
val alternative = z.groupBy(s => z.collect {
case other if similarity(s, other) < threshold => other
}.toSet ).values.toList
All of this assumes that the function:
f(a: String, b: String): Boolean = similarity(a, b) < threshold
Is commutative and transitive, i.e.:
f(a, b) && f(a. c) means that f(b, c)
f(a, b) if and only if f(b, a)
To test both implementations I used:
// strings are similar if they start with the same character
def similarity(s1: String, s2: String) = if (s1.head == s2.head) 0 else 100
val threshold = 1
val z = List("aa", "ab", "c", "a", "e", "fa", "fb")
And both options produce the same results:
List(List(aa, ab, a), List(c), List(e), List(fa, fb))

Reversible predicates and Strings in SWI-Prolog

append/3 is a very powerful predicate. Suppose I want a predicate that works the same way but for SWI-Prolog's strings.
The easiest approach I see is to transform those strings into lists with string_codes/2, then apply append/3, then use string_codes/2 back. The big problem with this approach is that string_codes/2 does not work if both variables are not unified.
Here is an extremely ugly solution I came up with, which checks which strings are unified to apply string_codes/2 when needed:
append_strings(S1, S2, S3) :-
nonvar(S1),
nonvar(S2),!,
string_codes(S1, A),
string_codes(S2, B),
append(A,B,C),
string_codes(S3, C).
append_strings(S1, S2, S3) :-
nonvar(S1),
nonvar(S3),!,
string_codes(S1, A),
string_codes(S3, C),
append(A,B,C),
string_codes(S2, B).
append_strings(S1, S2, S3) :-
nonvar(S2),
nonvar(S3),!,
string_codes(S2, B),
string_codes(S3, C),
append(A,B,C),
string_codes(S1, A).
append_strings(S1, S2, S3) :-
nonvar(S3),
string_codes(S3, C),
append(A,B,C),
string_codes(S1, A),
string_codes(S2, B).
This yields the correct results for the following cases:
?- append_strings("test","auie","testauie").
true.
?- append_strings("test",A,"testauie").
A = "auie".
?- append_strings(A,"auie","testauie").
A = "test" ;
false.
?- append_strings(A,B,"testauie").
A = "",
B = "testauie" ;
A = "t",
B = "estauie" ;
A = "te",
B = "stauie" ;
A = "tes",
B = "tauie" ;
A = "test",
B = "auie" ;
A = "testa",
B = "uie" ;
A = "testau",
B = "ie" ;
A = "testaui",
B = "e" ;
A = "testauie",
B = "" ;
false.
Is there really no way to make things simpler than this? Suppose I want to make a whole bunch of predicates that work with strings just like they would with lists: I obviously don't want to have to write what I did for append/3 for all of them. But I also don't want to work with code strings because then I have no way of knowing whether I am manipulating a normal list or really a string.
Since the predicate is working on lists, it seems tempting to me to use DCGs. First let's observe that strings in Prolog are really lists of character codes:
?- X="test".
X = [116,101,115,116]
Of course this is not very readable, so let's see the characters themselves intead of their codes:
?- set_prolog_flag(double_quotes,chars).
yes
?- X="test".
X = [t,e,s,t]
That's better. Thinking about the relation the predicate should describe, I opt for a descriptive name like list_list_appended/3. This predicate has one goal: a dcg-rule, let's call it list_list//2, that uses another dcg, let's call it list//2, to actually write the lists:
list_list_appended(L1,L2,L3) :-
phrase(list_list(L1,L2),L3). % L3 is L1+L2
list([]) --> % if the list is empty ...
[]. % ... there's nothing in the list
list([X|Xs]) --> % if there's a head element ...
[X], % ... it's in the list
list(Xs). % the tail is also a list
list_list(L1,L2) --> % the list consists of ...
list(L1), % ... L1 followed by ...
list(L2). % L2
Your example queries:
?- list_list_appended("test","auie","testauie").
yes
?- list_list_appended(L1,"auie","testauie").
L1 = [t,e,s,t] ? ;
no
?- list_list_appended("test",L2,"testauie").
L2 = [a,u,i,e] ? ;
no
?- list_list_appended("test","auie",L3).
L3 = [t,e,s,t,a,u,i,e]
?- list_list_appended(L1,L2,"testauie").
L1 = [],
L2 = [t,e,s,t,a,u,i,e] ? ;
L1 = [t],
L2 = [e,s,t,a,u,i,e] ? ;
L1 = [t,e],
L2 = [s,t,a,u,i,e] ? ;
L1 = [t,e,s],
L2 = [t,a,u,i,e] ? ;
L1 = [t,e,s,t],
L2 = [a,u,i,e] ? ;
L1 = [t,e,s,t,a],
L2 = [u,i,e] ? ;
L1 = [t,e,s,t,a,u],
L2 = [i,e] ? ;
L1 = [t,e,s,t,a,u,i],
L2 = [e] ? ;
L1 = [t,e,s,t,a,u,i,e],
L2 = [] ? ;
no
As a SWI user you could also use this library in combination with set_prolog_flag(double_quotes,chars). to get the output in desired form. Refer to this answer for details.
Just use string_concat/3. Like ISO atom_concat/3, it can be used in many modes, including (-,-,+).
This is a more compact definition:
append_strings(S1, S2, S3):-
append_strings1(S1, L1, [1]-[], N1),
append_strings1(S2, L2, [1|N1]-N1, N2),
append_strings1(S3, L3, [1,1|N2]-N2, N3),
(N3\=[_,_|_] ->instantiation_error(append_strings/3); true),
append(L1, L2, L3),
(ground(S1)->true;string_codes(S1, L1)),
(ground(S2)->true;string_codes(S2, L2)),
(ground(S3)->true;string_codes(S3, L3)).
append_strings1(S, L, G-NG, N):-
(ground(S) -> (string_codes(S, L), N=G) ; N=NG).
It checks whether each argument is ground and tries to convert to codes, then checks if either the third argument is ground or the other two are, and throws an instantiation error if conditions are not met.
After the append it converts back to string arguments which where not ground.
there has been a similar question some time ago, I will show my proposal, revised
:- meta_predicate when_(0).
when_(P) :-
strip_module(P,_,Q), Q =.. [_|As],
or_list(As, Exp), % hurry debugging :-) display(Exp),
when(Exp, P).
or_list([A], ground(A)) :- !.
or_list([A|As], (ground(A);Exp)) :- or_list(As, Exp).
append_strings(S1, S2, S3) :-
maplist(when_, [string_codes(S1, A), string_codes(S2, B), append(A,B,C), string_codes(S3, C)]).
If you are interested, I can add an operator to hide the syntax details, to get something like
append_strings(S1, S2, S3) -:-
string_codes(S1, A), string_codes(S2, B), append(A,B,C), string_codes(S3, C).

Are there any programming languages with functions with variable arguments not at the end?

Python, C++, Scheme, and others all let you define functions that take a variable number of arguments at the end of the argument list...
def function(a, b, *args):
#etc...
...that can be called as followed:
function(1, 2)
function(1, 2, 5, 6, 7, 8)
etc... Are there any languages that allow you to do variadic functions with the argument list somewhere else? Something like this:
def function(int a, string... args, int theend) {...}
With all of these valid:
function(1, 2)
function(1, "a", 3)
function(1, "b", "c", 4)
Also, what about optional arguments anywhere in the argument list?
def function(int a, int? b, int c, int... d) {}
function(1, 2) //a=1, c=2, b=undefined/null/something, d=[]
function(1,2,3) //a=1, b=2, c=3,d=[]
function(1,2,3,4,5) //a=1, b=2, c=3, d=[4,5]
The next C++ can do that with this syntax:
void f(int a, std::initializer_list<int> b, int c) {
// b.begin(), b.end(), b.size() allow to access them
}
void g() {
f(1, { 2, 3, 4, 5 }, 2);
}
BASIC has had this for ages.
For instance:
LOCATE [row%] [,[column%] [,[cursor%] [,start% [,stop%]]]]
This command sets the position (row%, column%) of the cursor, as well as specifying the cursor size (start%, stop%) and whether it is actually visible (cursor%). Here, everything in square brackets can be omitted, and if it is, that property is not changed.
A usage example:
LOCATE , 5
to change to column 5, or
LOCATE 1, , 0
to move to the first line and make the cursor invisible.
Another command where this is seen is the PUT command for writing to files. If the middle argument (the file seek position) is omitted then writing occurs just after the previous write.
Importantly, argument omission is only seen in built-in statements, and not user-defined procedures and functions.
In terms of implementation, this is what the Microsoft Basic Compiler (BC) seems to do for a call to LOCATE:
For each argument:
if an argument is omitted, push 0
if an argument is supplied, push 1, and then push the actual value
Push the argument count
Call the library function
Future versions of Ruby (1.9 and up, Ruby 1.9 is scheduled to released at the end of January, 2009) can do this.
It is however not always obvious which value gets bound to which parameter.
This is what Ruby 1.9 accepts:
0 or more mandatory arguments followed by 0 or more optional arguments followed by 0 or more mandatory arguments followed by rest arguments followed by 0 or more mandatory arguments.
Example:
def meth mand1, opt1 = :def1, o2 = :d2, *args, m2, m3
puts %w[mand1 opt1 o2 m2 args m3].inject('') { |s, arg|
s << "#{arg} = #{(eval arg).inspect}, "
}.gsub /, $/, ''
end
meth :arg1, :a2, :a3
# => mand1 = :arg1, opt1 = :def1, o2 = :d2, m2 = :a2, args = [], m3 = :a3
meth :arg1, :a2, :a3, :a4
# => mand1 = :arg1, opt1 = :a2, o2 = :d2, m2 = :a3, args = [], m3 = :a4
meth :arg1, :a2, :a3, :a4, :a5
# => mand1 = :arg1, opt1 = :a2, o2 = :a3, m2 = :a4, args = [], m3 = :a5
meth :arg1, :a2, :a3, :a4, :a5, :a6
# => mand1 = :arg1, opt1 = :a2, o2 = :a3, m2 = :a5, args = [:a4], m3 = :a6
meth :arg1, :a2, :a3, :a4, :a5, :a6, :a7
# => mand1 = :arg1, opt1 = :a2, o2 = :a3, m2 = :a6, args = [:a4, :a5], m3 = :a7
As you can see, mandatory arguments are bound first, from both the left and the right. Then optional arguments get bound and if any arguments are left over, they get bundled up in an array and bound to the rest argument.
Several languages (perl, python, many others) can do named arguments, which are akin to doing optional arguments anywhere in the parameter list... (The named parameters can appear in any order, and any of them can be made optional...) They're not strictly the same, but they're close...
Not sure about varargs, though they can usually be replaced with an array/hash/list object...
Lisp's keyword parameters may be what you are looking for. I think there is a similar arrangement in Ruby. See also Lisp's function parameters overview.
I suppose PHP counts. You can do this to simulate what you are looking for. Personally, I think that would be confusing though.
function foo() {
$args = func_get_args(); // returns an array of args
}
R (the statistical language) has it as well, and it can be in the middle of the list, but there are subtle semantics.
http://cran.r-project.org/doc/manuals/R-intro.html#The-three-dots-argument
> f1 <- function(x,...,y) { return(x+y) }
> f1(1,2)
Error in f1(1, 2) : argument "y" is missing, with no default
> f1(1,y=2)
[1] 3
> f1 <- function(x,...,y) { return(x+y) }
> f1(1,2)
Error in f1(1, 2) : argument "y" is missing, with no default
> f1(1,y=2)
[1] 3
>
It is called Rest Arguments and it can be done at least in C++ and Java. Google "Rest Arguments" and you will find a lot of data on the subject with some examples like functions that will pass numbers and return an average of the numbers input, maybe the minimum or maximum of all numbers passed. As you can see, there are a lot of uses for such features, I used it in code for inputing data in MYSQL so when I want to add a row, I just add the Table name as the first string and the rest are all column names and then their data without having to sit there and manually do it over and over again. Good Luck!

Resources