I cribbed from the hotel door lock example and came up with this MWE for vehicle doors.
enum LockState {Locked, Unlocked}
sig Door {
var state: LockState
}
sig Vehicle {
doors : disj set Door
}
//actions
pred unlock[d: Door]{
d.state' = Unlocked
}
pred lock[d: Door]{
d.state' = Locked
}
//traces
pred init{
all s: Door.state | s = Locked
}
pred trace{
init
always {
some d: Door |
unlock[d] or
lock[d]
}
}
//demonstrate
run {} for 4 but exactly 2 Vehicle, 4 Time
Which to my suprise allows the instance shown below, in which some doors are locked and some not. How do I establish the condition that all doors are locked at the earliest time?
Initial states are defined without any temporal keywords, as you did in init.
The problem is that you defined your trace as a predicate. If you define it as a fact it will always be applied. However, if you make it a predicate (my preference since it feels less global) you must include it from the run command. Pick one:
run trace for 4 but exactly 2 Vehicle, 4 Time
run { trace } for 4 but exactly 2 Vehicle, 4 Time
However, your model will then still not run well.
You provide an always but no goal. So after one state Alloy is happy. You should provide an eventually so Alloy will attempt to continue until it is satisfied.
You allow vehicles without doors, I would use some Door instead of set Door
Your init can be done cleaner like Door.state = Locked
In your trace, each step sets one Door. However, you're not specifying what the state of the other doors should be. If you do not specify a value for the next state, they can become anything. These should be explicitly set to have their old value.
So I came up with the following model:
enum LockState { Locked, Unlocked }
sig Door { var state: LockState }
sig Vehicle { doors : disj some Door }
pred Door.unlock { this.state' = Unlocked }
pred Door.lock { this.state' = Locked }
pred trace {
Door.state = Locked
always (
some d: Vehicle.doors {
(d.unlock or d.lock)
unchanged[state,d]
}
)
eventually Door.state = Unlocked
}
run trace for 4 but exactly 2 Vehicle
pred unchanged[ r : univ->univ, x : set univ ] {
(r - x->univ)' = (r - x->univ)
}
updated Added an unchanged predicate.
I am having errors in Alloy (4.2) specifications of the following kind:
You must specify a scope for sig "this/Univ"
The issue is easy to reproduce with a toy example:
open util/ordering[State]
open util/integer
sig State { value : Int }
fact {
first.value = 0
all s:State, s': s.next | s'.value = plus[s.value, 1]
}
run { } for 5 State, 3 Int
All of the above is fine. Now, when I define State in an external file and import it with an open statement, I get the "Univ scope" error:
open util/ordering[State]
open util/integer
open State
fact {
first.value = 0
all s:State, s': s.next | s'.value = plus[s.value, 1]
}
run { } for 5 State, 3 Int
I tried several variations of the above without success.
Why does this happen and how can it be solved?
In my project, it would be useful for me to define the target sig of the ordering module in a different file.
Thanks,
Eduardo
This is an Alloy "design bug".
It was decided that a Univ signature would appear when no signatures are defined in the module in order to check some property over built-in relations (e.g., unit, iden, none).
You have many ways of going around this problem, here is a selection :
You can add ",0 Univ" at the end of your run command
You can add a signature in your Alloy module
You can specify a global scope of zero (run { } for 0 but 5 State, 3 Int )
See this question for additional informations
I'd like to automate inserting comment snippets for C++ files. Google search suggested c.vim plugin. I installed it. Now when I create a file, I get template like following.
/* =====================================================================================
*
* Filename: Foo.h
*
* Description: :
*
* Version: 1.0
* Created: 04/14/2014 08:35:44 PM
* Revision: none
* Compiler: gcc
*
* Author: YOUR NAME (),
* Organization:
*
* =====================================================================================
*/
From :h csupport I catch I can create my own templates for comments. Is there simpler way to get doxygen-style comments in project? Or maybe these templates are available somewhere?
If you only need these comments and not the other features of c.vim, I'd recommend you to use some snippets plugin, such as Snipmate or Ultisnips. Creating such snippets with these plugins is very easy and they are very powerful.
You can use Doxygen plugin for vim. It's available here. Simply enter :Dox to add your comments.
For example,
/**
* #brief
*
* #param list
* #param size
* #param key
* #param rec
*
* #return
*/
bool jw_search ( int *list, int size, int key, int& rec )
{
return true;
}
lh-cpp & mu-template come with tunable project headers (the default is quite bad I have to admit). You'll have to override templates/c/internals/c-file-header.template to something like:
VimL: let s:filename = s:path_from_root(expand('%:p'))
VimL: let s:prj_dox_group = lh#option#get('my_prj_dox_group', lh#marker#txt('group'))
/**#file <+s:filename+>
* #ingroup <+s:prj_dox_group+>
* #author <+Author()+>
* <p>Licence:<p> Your Project Licence
*/
(All the other stuff is already taken care of: include guards will be added automatically in header files, and foo.h will be automatically included in foo.c(pp))
Then in a local_vimrc-like plugin, you'll have to set:
" File: /root/path/of/the/project/_vimrc_local.vim
:let b:my_prj_dox_group = "gMain" " you can override it in subfolders
:let b:sources_root = '/root/path/of/the/project' " for mu-template
:let b:includes = [b:sources_root . '/**'] " I can't remember which ftplugin uses b:includes
:let b:included_paths = [b:sources_root] " for ftplugin/c/c_AddInclude.vim
:let g:alternateSearchPath = 'sfr:.' " (or equivalent) for a.vim and for foo.cpp to include foo.h
BTW, lh-cpp also comes with the :DOX command that'll parse a function signature to automatically generate its doxygen caption (#param[in/out/0], #return, #ingroup, #throw (noexcept and the deprecated exception specifications are analysed), ... will be filled as automagically as possible)
If we take Saraht's example, it becomes:
/**
* «brief explanation».
* «details»
* #param[«in,»out] list «list-explanations»
* #param[in] size «size-explanations»
* #param[in] key «key-explanations»
* #param[«in,»out] rec «rec-explanations»
*
* #return «bool»
* «#throw »
* #pre <tt>list != NULL</tt>«»
*/
bool jw_search ( int* list, int size, int key, int& rec )
NB: «» occurrences mark placeholders
PS: I have no idea how it will behave if your keep c.vim as I don't use it.
This is an example of Alloy that I found I want to make it with 3 predicates, 3 facts, 3 objects and 3 assertions, can someone please help me? I am very new in Alloy and need some immediate help.
abstract sig Color {}
one sig Red,Yellow,Green extends Color {}
sig Light {
color: Color
}
sig Junction {
lights : set Light
}
fun count[j:Junction, c:Color] : Int {
#{x:Light | x in j.lights and x.color=c}
}
// This is just for realism, make sure each light belongs to exactly one junction
fact {
Light = Junction.lights
no x,y:Junction | x!=y and some x.lights & y.lights
Light = Junction.lights
no y,x:Junction | y!=x and some y.lights & x.lights
}
pred mostly[j:Junction, c:Color] {
no cc:Color | cc!=c and count[j,cc]>=count[j,c]
}
run{
some j:Junction | mostly[j,Red]
} for 10 Light, 2 Junction, 10 int`
In Alloy, you can only provide a scope for the number of objects (atoms) of each sig in your model. Predicates, functions, and assertions you write explicitly in your model, they are not "expanded" by the Alloy Analyzer in any way, and they cannot be quantified over, so providing a separate scope for them would not make sense.
I was wondering, is there any programming language where you can have function calls like this:
function_name(parameter1)function_name_continued(parameter2);
or
function_name(param1)function_continued(param2)...function_continued(paramN);
For example you could have this function call:
int dist = distanceFrom(cityA)to(cityB);
if you have defined distanceFromto function like this:
int distanceFrom(city A)to(city B)
{
// find distance between city A and city B
// ...
return distance;
}
As far as I know, in C, Java and SML programming languages, this cannot be done.
Are you aware of any programming language that let's you define and call
functions in this way?
It looks an awful lot like Objective-C
- (int)distanceFrom:(City *)cityA to:(City *)cityB {
// woah!
}
Sounds a lot like Smalltalk's syntax, (which would explain Objective-C's syntax - see kubi's answer).
Example:
dist := metric distanceFrom: cityA to: cityB
where #distanceFrom:to: is a method on some object called metric.
So you have "function calls" (they're really message sends) like
'hello world' indexOf: $o startingAt: 6. "$o means 'the character literal o"
EDIT: I'd said "Really, #distanceFrom:to: should be called #distanceTo: on a City class, but anyway." Justice points out that this couples a City to a Metric, which is Bad. There are good reasons why you might want to vary the metric - aeroplanes might use a geodesic while cars might use a shortest path based on the road network.)
For the curious, Agda2 has a similar, very permissive syntax. The following is valid code:
data City : Set where
London : City
Paris : City
data Distance : Set where
_km : ℕ → Distance
from_to_ : City → City → Distance
from London to London = 0 km
from London to Paris = 342 km
from Paris to London = 342 km
from Paris to Paris = 0 km
If
from Paris to London
is evaluated, the result is
342 km
Looks a lot like a fluent interface or method chaining to me.
In Python, you can explicitly pass the name of the arguments you're calling the function with, which lets you pass them in a different order or skip optional arguments:
>>> l = [3,5,1,2,4]
>>> print l.sort.__doc__
L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*;
cmp(x, y) -> -1, 0, 1
>>> l.sort (reverse=True)
>>> l
[5, 4, 3, 2, 1]
This looks a lot like what the Objective C syntax is doing, tagging each argument to a function with its name.
C# 4.0's Named and Optional Arguments feature allows you to achieve something pretty similar:
public static int Distance(string from, string to, string via = "")
{
...
}
public static void Main()
{
int distance;
distance = Distance(from: "New York", to: "Tokyo");
distance = Distance(to: "Tokyo", from: "New York");
distance = Distance(from: "New York", via: "Athens", to: "Tokyo");
}
(see my very favourite personal effort - the final C++ approach at the end of this answer)
Language One
Objective-C but the calling syntax is [object message] so would look like:
int dist = [cities distanceFrom:cityA to:cityB];
if you have defined distanceFromto function like this, within a cities object:
- (int)distanceFrom:(City *)cityA to:(City *)cityB
{
// find distance between city A and city B
// ...
return distance;
}
Language Two
I also suspect you could achieve something very close to this in the IO Language but I'm only just looking at it. You may also want to read about it in comparison to other languages in Seven Languages in Seven Weeks which has a free excerpt about IO.
Language Three
There's an idiom ("chaining") in C++ where you return temporary objects or the current object that is used to replace keyword arguments, according to The Design and Evolution of C++ and looks like this:
int dist = distanceFrom(cityA).to(cityB);
if you have defined distanceFrom function like this, with a little helper object. Note that inline functions make this kind of thing compile to very efficient code.
class DistanceCalculator
{
public:
DistanceCalculator(City* from) : fromCity(from) {}
int to(City * toCity)
{
// find distance between fromCity and toCity
// ...
return distance;
}
private:
City* fromCity;
};
inline DistanceCalculator distanceFrom(City* from)
{
return DistanceCalculator(from);
}
Duhh, I was in a hurry earlier, realised I can refactor to just use a temporary object to give the same syntax:
class distanceFrom
{
public:
distanceFrom(City* from) : fromCity(from) {}
int to(City * toCity)
{
// find distance between fromCity and toCity
// ...
return distance;
}
private:
City* fromCity;
};
MY FAVOURITE
and here's an even more inspired C++ version that allows you to write
int dist = distanceFrom cityA to cityB;
or even
int dist = distanceFrom cityA to cityB to cityC;
based on a wonderfully C++ ish combination of #define and classes:
#include <vector>
#include <numeric>
class City;
#define distanceFrom DistanceCalculator() <<
#define to <<
class DistanceCalculator
{
public:
operator int()
{
// find distance between chain of cities
return std::accumulate(cities.begin(), cities.end(), 0);
}
DistanceCalculator& operator<<(City* aCity)
{
cities.push_back(aCity);
return *this;
}
private:
std::vector<City*> cities;
};
NOTE this may look like a useless exercise but in some contexts it can be very useful to give people a domain-specific language in C++ which they compile alongside libraries. We used a similar approach with Python for geo-modeling scientists at the CSIRO.
You can do this in C, albeit unsafely:
struct Arg_s
{
int from;
int to;
};
int distance_f(struct Arg_s args)
{
return args.to - args.from;
}
#define distance(...) distance_f( ((struct Arg_s){__VA_ARGS__}) )
#define from_ .from =
#define to_ .to =
uses compound literals and designated initializers.
printf("5 to 7 = %i\n",distance(from_ 5, to_ 7));
// 5 to 7 = 2
3 of the 4 confederated languages from RemObjects in their Elements Compiler have this capability in precisely the OP's requested syntax (to support Objective-C runtime, but made available to all operating systems).
in Hydrogene (an extended C#)
https://docs.elementscompiler.com/Hydrogene/LanguageExtensions/MultiPartMethodNames
in Iodine (an extended Java)
https://docs.elementscompiler.com/Iodine/LanguageExtensions/MultiPartMethodNames
in Oxygene (an extended ObjectPascal), scroll down to Multi-Part Method Names section
https://docs.elementscompiler.com/Oxygene/Members/Methods
This looks similar to function overloading (C++/C#)/default parameters (VB).
Default Parameters allow the person defining the function to set defaults for the latter parameters:
e.g. c# overloading:
int CalculateDistance(city A, city B, city via1, city via2)
{....}
int CalculateDistance(city A, city B)
{
return CalculateDistance(city A, city B, null, null)
}
You can use a member function for this.
cityA.distance_to(cityB);
That's valid code in C++, C(with a little tweaking), C#, Java. Using method chains, you can do:
cityA.something(cityB).something(cityC).something(cityD).something(cityE);
In SML you could simply make "to" some value (unit, for example), and "distanceFrom" a curried function that takes three parameters. For example:
val to = ()
fun distanceFrom x _ y = (* implementation function body *)
val foo = distanceFrom cityA to cityB
You could also take advantage of the fact that SML doesn't enforce naming conventions on datataype constructors (much to many peoples' annoyance), so if you want to make sure that the type system enforces your custom syntax:
datatype comp = to
fun distanceFrom x to y = (* implementation *)
val foo = distanceFrom cityA to cityB (* works *)
val foo' = distanceFrom cityA cityB (* whoops, forgot 'to' - type error! *)
You could do this in Scheme or LISP using macros.
The form will be something like:
(DISTANCE-FROM city-a TO city-b)
The symbols in uppercase denotes syntax.
You could even do something like 'named parameters':
(DISTANCE TO city-a FROM city-b)
(DISTANCE FROM city-a TO city-b)
Tcl allows you to do something like this:
proc distance {from cityA to cityB} {...}
set distance [distance from "Chicago IL" to "Tulsa OK"]
I'm not sure if that's quite what you are thinking of though.
You can do it in Java, Use Builder pattern that appears in the book Effective Java by Joshua Bosch (this is second time I put this link in SO, I still didn't use that patern, but looks great)
Well, in Felix you can implement this in two steps: first, you write an ordinary function. Then, you can extend the grammar and map some of the new non-terminals to the function.
This is a bit heavyweight compared to what you might want (welcome to help make it easier!!) I think this does what you want and a whole lot more!
I will give a real example because the whole of the Felix language is actually defined by this technique (below x is the non-terminal for expressions, the p in x[p] is a precedence code):
// alternate conditional
x[sdollar_apply_pri] := x[stuple_pri] "unless" x[let_pri]
"then" x[sdollar_apply_pri] =>#
"`(ast_cond ,_sr ((ast_apply ,_sr (lnot ,_3)) ,_1 ,_5))";
Here's a bit more:
// indexes and slices
x[sfactor_pri] := x[sfactor_pri] "." "[" sexpr "]" =>#
"`(ast_apply ,_sr (,(noi 'subscript) (,_1 ,_4)))";
x[sfactor_pri] := x[sfactor_pri] "." "[" sexpr "to" sexpr "]" =>#
"`(ast_apply ,_sr (,(noi 'substring) (,_1 ,_4 ,_6)))";
x[sfactor_pri] := x[sfactor_pri] "." "[" sexpr "to" "]" =>#
"`(ast_apply ,_sr (,(noi 'copyfrom) (,_1 ,_4)))";
x[sfactor_pri] := x[sfactor_pri] "." "[" "to" sexpr "]" =>#
"`(ast_apply ,_sr (,(noi 'copyto) (,_1 ,_5)))";
The Felix grammar is ordinary user code. In the examples the grammar actions are written in Scheme. The grammar is GLR. It allows "context sensitive keywords", that is, identifiers that are keywords in certain contexts only, which makes it easy to invent new constructs without worrying about breaking existing code.
Perhaps you would like to examine Felix Grammar Online.