How to evaluate a predicate in Alloy source code? - alloy

I have a predicate in my Alloy model, called LS, which gets an instance of a sig called st. I am trying to evaluate this predicate on an instance of st, called st$0, in the source code. I can find the solution of type A4Solution, called ans. But I don't know how I can evaluate this predicate on this solution.

Here is how you can in general evaluate predicates using the API
String fileName = "<file path to your alloy model>";
Module world = CompUtil.parseEverything_fromFile(rep, null, fileName);
A4Options opt = new A4Options();
opt.solver = A4Options.SatSolver.SAT4J;
// run the first command for the sake of this example
Command cmd = world.getAllCommands().get(0);
A4Solution sol = TranslateAlloyToKodkod.execute_command(rep, world.getAllReachableSigs(), cmd, opt);
// evaluate the first defined function/predicate applied to the first defined Sig
Func func = world.getAllFunc().get(0);
Sig sig = world.getAllSigs().get(0);
System.out.println(sol.eval(func.call(sig)));

Related

Simplify incomplete assertions in HSpec

I want to unit-test a function that returns a complex nested data structure, but I'm only interested in certain fields of that structure. For example:
expectedResult = Right (
UserRecord {
name = "someName",
id = <don't care>
address = AddressRecord {
street = "someStreet",
id = <don't care>
}
}
)
Is there a generic way to assert a result of the above form in HSpec? That is, some way to write an expression
result `shouldBe` expectedResult
where I do not need to specify those parts of the expected result that I am not interested in? I found this answer, which requires to copy over all don't care fields from result to expectedResult; this might get rather tedious. Maybe there is a standard approach using lenses? Or some library with assertion helpers I haven't heard of?
A simple approach:
result `shouldSatisfy` \a ->
name a == "someName" &&
street (address a) == "someStreet"

Groovy: Constructor hash collision

I have the following groovy code:
def script
String credentials_id
String repository_path
String relative_directory
String repository_url
CredentialsWrapper(script, credentials_id, repository_name, repository_group, relative_directory=null) {
this(script, credentials_id, 'git#gitlab.foo.com:' + repository_group +'/' + repository_name + '.git', relative_directory);
}
CredentialsWrapper(script, credentials_id, repository_url, relative_directory=null) {
this.script = script;
this.credentials_id = credentials_id;
this.repository_url = repository_url;
if (null == relative_directory) {
int lastSeparatorIndex = repository_url.lastIndexOf("/");
int indexOfExt = repository_url.indexOf(".git");
this.relative_directory = repository_url.substring(lastSeparatorIndex+1, indexOfExt);
}
}
Jenkins gives me the following:
Unable to compile class com.foo.CredentialsWrapper due to hash collision in constructors # line 30, column 7.
I do not understand why, the constructors are different, they do not have the same number of arguments.
Also, "script" is an instance from "WorkflowScript", but I do not know what I should import to access this class, which would allow me to declare script explicitly instead of using "def"
Any idea ?
When you call the Constructor with four parameters, would you like to call the first or the second one?
If you write an constructor/method with default values, groovy will actually generate two or more versions.
So
Test(String x, String y ="test")
will result in
Test(String x, String y) {...}
and
Test(String x) {new Test(x, "test")}
So your code would like to compile to 4 constructors, but it contains the constructor with the signature
CredentialsWrapper(def, def, def, def)
two times.
If I understand your code correctly, you can omit one or both of the =null. The result will be the same, but you will get only two or three signatures. Then you can choose between both versions by calling calling them with the right parameter count.

How to use function by having its name as a string

Suppose you want to use a sequence of functions defined in MATLAB, and you just have the name of those functions as string variables. Let say you have already created fun1, fun2, ...,funN, and you also have a vector of strings as ['fun1','fun2',...,'funN']. How to call each function automatically without being forced to write name of each function one by one?
Use str2func. Of course, if the functions have been defined as function handles (e.g. fun1 = #(x)x+x.^2+sqrt(x))), you can skip the str2func step below.
strList= {'sum','mean','max','min'};
funList = cellfun(#str2func,strList,'uniformOutput',false);
nFunctions = length(funList);
data = rand(10,1);
results = zeros(nFunctions,1)
for iFunction = 1:nFunctions
results(iFunction) = fulList{iFunction}(data);
end

ocaml object with external function as method

Sometimes one wants to write bindings for some C code using ocaml modules as interface or optimize some method of an object in C. But one can't define the external function before the object because it needs the type of the object and one can't define the object because it needs to call the external function.
One solution is to use recursive modules but that easily tripples the source size and becomes awfully unreadable. The external functions also enter the modules namespace and need to be hidden again. So what is a shorter, more readable solution?
I figured out how to use first class modules to define an external function directly inside an objec. First one needs an module type to be used by the first class module. This is generic and can be used for any kind of external function over and over:
module type External = sig
type e
val stub : e
end
after that once can declare external functions like this:
class c =
let ext = (module struct
type e = c -> unit
external stub : c -> unit = "stub"
end : External with type e = c -> unit)
in
object(self:'self)
method as_c = (self :> c)
method foo =
let module E = (val ext)
in
E.stub self#as_c
end
or even more local within the method itself as:
class c = object(self:'self)
method as_c = (self :> c)
method foo =
let module E = (val (module struct
type t = c -> unit
external stub : c -> unit = "stub"
end) : External with type t = c -> unit)
in
E.stub self#as_c
end
Note: the as_c method avoids the (open) self type getting closed or escaping its scope.

Haskell: Need Enlightenment with Calculator program

I have an assignment which is to create a calculator program in Haskell. For example, users will be able to use the calculator by command lines like:
>var cola =5; //define a random variable
>cola*2+1;
(print 11)
>var pepsi = 10
>coca > pepsi;
(print false)
>def coke(x,y) = x+y; //define a random function
>coke(cola,pepsi);
(print 15)
//and actually it's more complicated than above
I have no clue how to program this in Haskell. All I can think of right now is to read the command line as a String, parse it into an array of tokens. Maybe go through the array, detect keywords such "var", "def" then call functions var, def which store variables/functions in a List or something like that. But then how do I store data so that I can use them later in my computation?
Also am I on the right track because I am actually very confused what to do next? :(
*In addition, I am not allowed to use Parsec!*
It looks like you have two distinct kinds of input: declarations (creating new variables and functions) and expressions (calculating things).
You should first define some data structures so you can work out what sort of things you are going to be dealing with. Something like:
data Command = Define Definition | Calculate Expression | Quit
type Name = String
data Definition = DefVar Name Expression | DefFunc Name [Name] Expression
-- ^ alternatively, implement variables as zero-argument functions
-- and merge these cases
data Expression = Var Name | Add Expression Expression | -- ... other stuff
type Environment = [Definition]
To start off with, just parse (tokenise and then parse the tokens, perhaps) the stuff into a Command, and then decide what to do with it.
Expressions are comparatively easy. You assume you already have all the definitions you need (an Environment) and then just look up any variables or do additions or whatever.
Definitions are a bit trickier. Once you've decided what new definition to make, you need to add it to the environment. How exactly you do this depends on how exactly you iterate through the lines, but you'll need to pass the new environment back from the interpreter to the thing which fetches the next line and runs the interpreter on it. Something like:
main :: IO ()
main = mainLoop emptyEnv
where
emptyEnv = []
mainLoop :: Environment -> IO ()
mainLoop env = do
str <- getLine
case parseCommnad str of
Nothing -> do
putStrLn "parse failed!"
mainLoop env
Just Quit -> do
return ()
Just (Define d) -> do
mainLoop (d : env)
Just (Calculate e) -> do
putStrLn (calc env e)
mainLoop env
-- the real meat:
parseCommand :: String -> Maybe Command
calc :: Environment -> Expression -> String -- or Integer or some other appropriate type
calc will need to look stuff up in the environment you create as you go along, so you'll probably also need a function for finding which Definition corresponds to a given Name (or complaining that there isn't one).
Some other decisions you should make:
What do I do when someone tries to redefine a variable?
What if I used one of those variables in the definition of a function? Do I evaluate a function definition when it is created or when it is used?
These questions may affect the design of the above program, but I'll leave it up to you to work out how.
First, you can learn a lot from this tutorial for haskell programming
You need to write your function in another doc with .hs
And you can load the file from you compiler and use all the function you create
For example
plus :: Int -> Int -- that mean the function just work with a number of type int and return Int
plus x y = x + y -- they receive x and y and do the operation

Resources