How do I add an if statement to the postcondition of a schema? - if-statement

I'll simplify things for this scenario (It's in Perfect Developer, it gets complex quite quickly). Let's say I have a simple schema in my class, called Succeed, which takes a Course (which is a previously defined class) as parameter.
Basically, I want to be sure that the course is in my courses set as a precondition, and then add it to my coursesCompleted set in my postcondition. This simple schema works great, and looks like this :
schema !Succeed(c:Course)
pre
c in allCourses
post
coursesCompleted! = coursesCompleted.append(c);
However, I want to add a quite simple if condition: If my coursesCompleted cardinality is 30 or more, I want to set a Diplomation enum to, let's say, "Ok". If the cardinality is less than 30, I will set it to "NotOk"
According to Perfect Developer's documentation, and all the rare examples I've seen, the if syntax should look like this :
if [condition1] : do stuff;
[condition2] : do other stuff;
fi
However, if I plug that directly in my schema, as is :
schema !Succeed(c:Course)
pre
c in allCourses
post
coursesCompleted! = coursesCompleted.append(c),
if [#coursesCompleted >= 30] : diplomation = Ok#DiplomationEnum;
[#coursesCompleted < 30] : diplomation = NotOk#DiplomationEnum;
fi
it does not work, I always end up with a "very descriptive"
Error! Syntax error at keyword 'if', expected one of: '!' '(' '?'
'c_address_of'
I've tried adding some ; everywhere, adding a via keyword after the post, changing it's position, trading ;s with ,, and a lot of other trial and error stuff.
So my question is: How can I add a if condition to a postcondition of a schema, in Perfect Developer?
Please answer in Perfect Developer. I (sadly) know my formal methods, I only need the if to compile in the worst tool in the world.

I can provide a solution in formal-methods using the zet notation, since I am not using Perfect Developer, however, that program should be based on formal-methods. As far as I know in formal methods, if conditions are not used when the system has different behavior over some preconditions, but rather you create 2 methods with different
preconditions(the way i implemented it) or a nested method covering both scenarios, seperated with a Logic OR in between. When it comes to error handling, you first provide a best case scenario and then define a robust method definition(schema calculus).
In formal methods the notation ! is used to describe the output while ? is used for the input.
I hope that this will help you understand possible issues, since its not a direct perfect-developer solution. However, considering the fact that in formal methods mathematics are used, you can use the following specification and jump to any program/language for the implementation part.
Note that: Anything that you will see in the following schemata on the preconditions/how the system changes part, is connected with a logic AND, however I am not using the symbol because is implied as far as a logic OR is not used.
So here is how it will look like in formal-methods(Z-notation).

Related

Spock test: Can when/then block labels be omitted (keeping code formerly separated by labels)? Are the labels syntax sugar?

In Spock testing, are the when: and then: block labels (labels themselves, not the code/phases they separate) strictly necessary? Or are they technically just syntactic sugar, that can be omitted (while still having/keeping the code lines that would otherwise be separated by the labels)?
I'm not sure if the stimulus/response phases (respective to when/then) still execute the same, when omitting the labels?
(I am curious to ask this, for the purpose of possibly saving a few lines of code; that may be relatively trivial, but I appreciate if anyone who can answer would humor me. I am in a context where there are no non-technical or less-technical users reading or writing Spock tests - I respect other contexts where including labels aids in readability for the other non/less-technical users; that makes sense.)
For example (1), consider the below feature method:
def "a feature method with when/then labels"(){
// setup phase code
when:
// stimulus phase code
then:
// response phase code
where:
// data table
}
Would the below (example 2) edit (of above example, removing just the when/then labels) be still functionally equivalent to above?
def "a feature method withOUT when/then labels"(){
// setup phase code
// stimulus phase code
// response phase code
where:
// data table
}
I have at least partially convinced myself they are equivalent, with my own before/after testing (of an edit like above) that "appears" to me to function the same (per its results) - but I am not sure if the respective stimulus/response phases still execute the same, when omitting the labels. Despite the identical results from my own testing I mentioned, I'm not sure if there may be differentiating side-effects that may not be so immediately apparent from the results themselves.
I wouldn't be surprised if example 2 above constitutes everything above its where block, to be in its implicit given block. But even if so, I'm not sure if that would make a difference, per the two examples being functionally equivalent or not.
Here's a few when/then block pair facts (for general context for others):
If you write one of the {when, then} labels, you must write the other - they always exist in [adjacent] pairs. Can't just write when: or just then: (for a given pair of stimulus/response phases)
Multiple when/then block pairs within the same feature method are perfectly fine
A feature method must always have at least 1 labeled block (per this, I think it doesn't matter which one)
I suggest you read the Spock manual. The blocks carry semantics and based on how you structure them the Groovy compiler will apply AST (abstract syntax tree) transformations upon your Spock specifications.
Why would you use Spock and try to cast away the very semantics delivered to you by this tool? If you don't like the behaviour-driven structure of Spock tests, just use pure Java or Groovy tests and the tool of your choice, such as JUnit or TestNG. But then if you wish to use mocks you need additional mock tools which, ironically, often re-introduce a behaviour-driven when-then or given-expect type of structure.
Minimally, as you noticed, you need at least one Spock-specific block in order for the test to be identified as a feature method. While you could omit given|setup and just use expect instead of when-then, this is only applicable to cases in which it makes sense. Try not to force everything into that structure but also use the other block types in order to clearly describe each feature in your specification. Technically, a then|expect block brings you the semantic of automatic assertions for all specified conditions (without having to use assert or a JUnit method like assertEquals). A where block brings you easy feature method parametrisation. An optional cleanup block helps you to close and/or clean up test resources cleanly without having to manually use try-finally constructs.
I suggest you learn how to use Spock as a tool correctly and enjoy its features instead of somehow trying to work around it, which would make using it rather pointless.

Unit testing higher order functions in F#

Take the following F# example:
let parse mapDate mapLevel mapMessge (groups : string list) =
{
DateTime =
mapDate(
groups.[2] |> Int32.Parse,
groups.[0] |> Int32.Parse,
groups.[1] |> Int32.Parse)
Level = mapLevel groups.[3]
Message = mapMessge groups.[4]
}
I can unit test the map functions independently that's ok, but how do I unit test that this function calls the functions passed in as arguments correctly?
In C# I would use mocks and verify the calls to them. I recently watched a pluralsight video that talked about how functional languages tend to use stubs instead of mocks. Here I could pass in a function that throws if it doesn't get the expected arguments but I'm not really sold on this approach.
I was just wondering if there were any patterns in functional programming in general for unit testing higher-order functions like this?
Well, let me disagree with given answer. Actually, there is a nice way to test higher order functions without even bothering about concrete types they might take (I consider typical HOF to be totally generic, however there is no difference: approach I suggest will work with more strict HFO rightly).
Let's take something really simple, something everyone is familiar with. How about ['t] -> ['t] function? It takes a single argument - a list of whatever type and returns list of the same type. Traditional OOP approach wouldn't work here: one need's to put a restriction on 't and test somewhat specific parameters of that type; the only way to make author to feel more confident with his implementation, is to increase unit tests numbers.
There is really great stuff named "category theory" in math. It's comparatively new filed of mathematics and studies things from the outside rather from than inside. In order to be able to describe things "from the outside" you need take a thing you're interested in and force it to interact with something you already know deep enough. Thus, category theory teaches to describe things in terms of their interrelations with other things. Can't we do the same here?..
Indeed, we can. That's actually quite easy: we got a f : ['t] -> ['t] already, but is there anything else such that we could make both interact and define something common - something that holds for each and every interaction regardless of any other factors? Let's take any g: 't -> 'y. Now we able to state: g (List.head (f ...) = List.head (List.map g (f ...)). I assume a certain argument of type ['t] to substitute .... Please note: given property is universal: it would hold for any pure functions composition of specified signatures regardless of their implementation. Also note how generic yet obvious it is: there are only two distinct "objects" interacting with each other via "composition", which could also be rewritten in terms of standard F#'s (|>), (<|) operators.
Now the fact is that for any higher order (pure) function there exists such kind of universal property; mostly, there are dozens of them. Thus one able to specify their properties in terms of composition (which is regular for FP) staying at the generic level. Having such a properties in the explicit form gives one chance to autogenerate hundreds of tests, based on inputs different not only by their values (which normally done by unit tests, except the fact they are rarely autogenerated), but also by types.
Pure functions are easier because you just have to test the outputs of your parse function. You shouldn't ever need to test using side effects like you do in imperative programming.
When writing most of your unit tests, you generally use the most simple possible for your function arguments, like identity or similar. Then you'd write one test named something like "mapLevel is applied to fourth group" where instead you make mapLevel something that's easy to recognize as changed, like toUpper. This lets you make sure you didn't accidentally copy/paste mapLevel to more than one output. Then a similar test for mapMessge.

Message receive for c++ actor system

I am trying to implement message handling for actors in c++. The following code in scala is something I am trying to implement in c++
def receive = {
case Message1 =>{/* logic code */}
case Message2 =>{/* logic code */}
}
Thus the idea is to create a set of handler functions for the various message type and create a dispatch method to route the message to its appropiate message handler. All messages will extends the base message type.
What would be the best approach to solve this problem:
Maintain a Map(Message_type, function_pointer), the dispatch method will check the map and call the appropiate method. This mapping however needs to be done mannually in the Actor class.
I read this library, the lbrary is handling message exactly as I want to but I cant understand how they do pattern matching on the lambda fucntions created on line 56.
I would appreciate any suggestion or reading links that could get me closer to the solution of this problem.
Since you've already mentioned CAF: why do you want to implement your own actor library instead of using CAF? If you are writing the lib as an exercise, I suggest start reading libcaf_core/caf/match_case.hpp, libcaf_core/caf/on.hpp and libcaf_core/caf/detail/try_match.hpp. This is the "core" of CAF's pattern matching facility. Be warned, you will be looking at a lot of metaprogramming code. The code is meant to be read by C++ experts. It's definitely not a good place to learn the techniques.
I can outline what's going on, though.
CAF stores patterns as a list of match_case objects in detail::behavior_impl
You never get a pointer to either one as user
message_handler and behavior store a pointer to behavior_impl
Match cases can be generated differently:
Directly from callbacks/lambdas (trivial case)
Using a catch-all rule (via others >> ...)
Using the advanced on(...) >> ... notation
CAF can only match against tuples stored in message objects
"Emulates" (a subset of) reflections
Values and meta information (i.e. type information) are needed
For the matching itself, CAF simply iterates over the list of match_case objects
Try match the input with each case
Stop on first match (just like functional languages implement this)
We put a lot of effort into the pattern matching implementation to get a high-level and clean interface on the user's end. It's not easy, though. So, if you're doing this as an exercise, be warned that you need a lot of metaprogramming experience to understand the code.
In case you don't do this as an exercise, I would be interested why you think CAF does not cover your use case and maybe we can convince you to participate in its development rather than developing something else from scratch. ;)
Try to use sobjectizer (batteries included) or rotor(still experimental, but quite lightweight actor-like solution).

How to make API names into variables for easier coding

I am looking for a way to turn some long and confusing API function names into shorter types to reduce the amount of typing and over all errors due to misspelling.
For example : I would like to take gtk_functionName(); and make it a variable like so. doThis = gtk_functionName;
Sometimes the code will have lots of repeating suffix. I want to know if I can take this g_signal_connect_ and turn it into this connect so I could just type connectswapped instead of g_signal_connect_swapped.
I am looking to do this in C\C++ but would be happy to know how its done in any language. I thought I had seen a code that did this before but I can not figure out what this would be called so searching for it has been fruitless.
I am sure this is possible and I am just not able to remember how its done.
I believe what you are wanting to do is apply the Facade Pattern, which is to present a simplified interface to a larger, more complex body of code.
What this basically means is you define your own simplified interfaces for the functionality you want. The implementation of these interfaces use the longer more complex packages you want to simplify. After that, the rest of your code use the simplified interfaces instead of the complex package directly.
void doThis (That *withThat) {
gtk_functionName(withThat->arg1, withThat->arg2 /* etc. */);
}

Parsing different xml messages. Versions

Say we want to Parse a XML messages to Business Objects. We split the process in two parts, namely:
-Parsing the XML messages to XML Grammar Objects.
-Transform XML Objects to Business Objects.
The first part is done automatically, generation a grammar object for each node.
The second part is done following the XML architecture so far. Example:
If we have the XML Message(Simplified):
<Main>
<ChildA>XYZ</ChildA>
<ChildB att1="0">
<InnerChild>YUK</InnerChild>
</ChildB>
</Main>
We could find the following classes:
DecodeMain(Calls DecodeChildA and B)
DecodeChildA
DecodeChildB(Calls DecodeInnerChild)
DecodeInnerChild
The main problem arrives when we need to handle versions of the same messages. Say we have a new version where only DecodeInnerChild changes(e.g.: We need to add an "a" at the end of the value)
It is really important that the solutions agile for further versions and as clean as possible. I considered the following options:
1)Simple Inheritance:Create two classes of DecodeInnerChild. One for each version.
Shortcomming: I will need to create different classes for every parent class to call the right one.
2)Version Parameter: Add to each method an Object with the version as a parameter. This way we will know what to do within each method according to each version.
Shortcoming: Not clean at all. The code of different versions is mixed.
3)Inheritance + Version Parameter: Create 2 classes with a base class for the common code for the nodes that directly changes (Like InnerChild) and add the version as a parameter in each method. When a node call the another class to decode the child object, it will use one or another class depending on the Version parameter.
4)Some kind of executor pattern(I do not know how to do it): Define at the start some kind of specifications object, where all the methods that are going to be used are indicated and I pass this object to a class that is in charge of execute them.
How would you do it? Other ideas are welcomed.
Thanks in advance. :)
How would you do it? Other ideas are welcomed.
Rather than parse XML myself I would as first step let something like CodesynthesisXSD to generate all needed classes for me and work on those. Later when performance or something becomes issue I would possibly start to look aound for more efficient parsers and if that is not fruitful only then i would start to design and write my own parser for specific case.
Edit:
Sorry, I should have been more specific :P, the first part is done
automatically, the whole code is generated from the XML schema.
OK, lets discuss then how to handle the usual situation that with evolution of software you will eventually have evolved input too. I put all silver bullets and magic wands on table here. If and what you implement of them is totally up to you.
Version attribute I have anyway with most things that I create. It is sane to have before backward-compatibility issue that can not be solved elegantly. Most importantly it achieves that when old software fails to parse newer input then it will produce complaint that makes immediately sense to everybody.
I usually also add some interface for converter. So old software can be equipped with converter from newer version of input when it fails to parse that. Also new software can use same converter to parse older input. Plus it is place where to plug converter from totally "alien" input. Win-win-win situation. ;)
On special case of minor change I would consider if it is cheap to make new DecodeInnerChild to be internally more flexible so accepts the value with or without that "a" in end as valid. In converter I have still to get rid of that "a" when converting for older versions.
Often what actually happens is that InnerChild does split and both versions will be used side-by-side. If there is sufficient behavioral difference between two InnerChilds then there is no point to avoid polymorphic InnerChilds. When polymorphism is added then indeed like you say in your 1) all containing classes that now have such polymorphic members have to be altered. Converter should usually on such cases either produce crippled InnerChild or forward to older version that the input is outside of their capabilities.