How to use UNION type to receive different types in one CPN place? - petri-net

I want to use a union in a way a place can receive two different types of "request", in my Coloured Petri Net model.
I have the following declarations:
colset AUTHENTICATION = product INT * STRING;
colset REQUEST_PUB = product AUTHENTICATION * STRING * REAL;
colset REQUEST_SUB = product AUTHENTICATION * STRING * INT;
colset REQUEST_PUBSUB = union REQUEST_PUB + REQUEST_SUB;
I have the following configuration:
Transition ------> Place (REQUEST_PUBSUB) <------ Transition
The right transition is sending ((int, string), string, real) and the left transition is sending ((int, string), string, int). Since the place is of type REQUEST_PUBSUB, which is a union of REQUEST_PUB and REQUEST_SUB, theoretically this should work, once ((int, string), string, real) is clearly a valid REQUEST_PUB and ((int, string), string, int) is clearly a valid REQUEST_SUB.
But this is not working and I am receiving the following errors:
Error: expression doesn't match constraint [tycon mismatch]
expression: (INT * STRING) * STRING * REAL
constraint: REQUEST_PUBSUB ms
in expression ((int, string), string, real): REQUEST_PUBSUB ms
Elaborate failure
And
Error: expression doesn't match constraint [tycon mismatch]
expression: (INT * STRING) * STRING * INT
constraint: REQUEST_PUBSUB ms
in expression ((int, string), string, int): REQUEST_PUBSUB ms
Elaborate failure
Can anyone help me with this? I think the description is clear, but I can complement it with more information if necessary.

I solved it specifying the identifiers for the union types:
colset REQUEST_PUBSUB = union pub_req:REQUEST_PUB + sub_req:REQUEST_SUB;
Then, for right transition arc I used pub_req((int, string), string, real) and for left transition arc I used sub_req((int, string), string, int).

Related

invalid operands of types 'const char [35]' and 'double' to binary 'operator+'

I have a problem with a string in arduino. I know that I can not put together different types like that. I have tried several conversions but don't get it working.
The following line is where I get the message "invalid operands of types 'const char [35]' and 'double' to binary 'operator +'"
sendString("Time: " + (micros () - PingTimer) * 0.001, 3 + " ms");
Disclaimer: This question is pretty similar but on a different stack exchange site (and the answer is questionable).
The problem can be reduced to the following snippet:
void setup() {
"hello" + 3.0;
}
It produces the following error message:
error: invalid operands of types 'const char [6]' and 'double' to binary 'operator+'
Many programming languages support "adding" character sequences together, C++ doesn't. Which means that you will need to use a class which represents a character sequence and implements the + operator.
Luckily there is already such a class which you can use: String. Example:
void setup() {
String("hello") + 3.0;
}
The expression is evaluates from left to right which means that the left most type has to be a String, in other words:
String("a") + 1 + 2 + 3
Is understood as:
((String("a") + 1) + 2) + 3
Where String("a") + 1 is a String and therefore (String("a") + 1) + 2 is, and so on...

XCTest'ing a tuple

I am trying to build a unit test like so:
// region is a (Double, Double) tuple
XCTAssertEqual(region, (0.0, 200.0))
But Xcode is giving me an error: Cannot invoke 'XCTAssertEqual' with an argument list of type ((Double, Double), (Double, Double))
Is there a different way to test tuples without extracting their members and testing individually?
XCTAssertEqual requires that the two parameters passed to it are Equatable, which you can see from the method signature. Note that expression1 returns T?, and T must be Equatable:
func XCTAssertEqual<T : Equatable>(_ expression1: #autoclosure () throws -> T?, _ expression2: #autoclosure () throws -> T?, _ message: #autoclosure () -> String = default, file: StaticString = #file, line: UInt = #line)
But Swift tuples aren't Equatable, so you can't use them with XCTAssertEqual.
Tuples do have an == method — they just don't conform to the protocol — so you could do something like this:
let eql = region == (0.0, 200.0)
XCTAssertTrue(eql)
Or even:
XCTAssertTrue(region == (0.0, 200.0))
Edit: I've expanded on this answer in a blog post, How to Make Specialized Test Assertions in Swift
A disadvantage of using
XCTAssertTrue(region == (0.0, 200.0))
is the inadequate reporting it gives upon failure:
XCTAssertTrue failed -
Now you have to track down what the actual values are, to understand what went wrong.
But you can add diagnostic information to the assertion like this:
XCTAssertTrue(region == (0.0, 200.0), "was \(region)")
For example:
XCTAssertTrue failed - was (1.0, 2.0)
If you plan to have several tests that compare this tuple, I wouldn't want to have to repeat this everywhere. Instead, create a custom assertion:
private func assertRegionsEqual(actual: (_: Double, _: Double), expected: (_: Double, _: Double), file: StaticString = #file, line: UInt = #line) {
if actual != expected {
XCTFail("Expected \(expected) but was \(actual)", file: file, line: line)
}
}
Now the test assertion is
assertRegionsEqual(actual: region, expected: (0.0, 200.0))
Upon failure, this yields a message like
failed - Expected (0.0, 200.0) but was (1.0, 2.0)

Discriminated union type checking in F# with differernt return types

I am trying to write an interpreter in F#. I want to check the type of expressions.
Here is my discriminated union for the expressions
type Expr =
| Integer of int
| String of string
| Boolean of bool
This is the method i am using to check the types with
let checkType (e:Expr) =
match e with
| String s -> s
| Integer i -> i
| Boolean b -> b
I want the method to determine wether an expression is a string,integer or boolean.
However, visual studio gives me the following error on line 4 of the checkType method:
This expression was expected to have type string but here has type int
Am i missing something?
To expand on John Palmer's comment:
F# expects each function to have a single return type. For example, you can write a function that takes an int and returns an int, which would be a function of type int -> int. A function that parses strings into ints would be of type string -> int. And so on.
Now, what is the return type of the checkType function you've written? Since you don't specify a return type, the compiler looks at the type of the values you can return from the function -- every possible code branch must return a value, and they must all be the same type. So it looks at your match statement, sees that its first branch returns a string, and says, "Ah ha! I've figured out the return type of this function; this is a function that takes an Expr and returns a string. The function's type is Expr -> string."
Then it looks at the second branch of your match statement, and says, "Wait a minute. This is a function that returns a string, but in this code branch it's returning an int. That's not valid: the code that calls this function needs to know what type to expect it to return." And so you get the error.
Now, if you were to swap the order of your match statement cases, checking for Integer i first, then the compiler would evaluate your function as having type Expr -> int (taking an Expr input and returning an int output), and throw an error on the | String s -> s line. This time, the error would be "Wait a minute, this is a function that returns an int, so the expression s here should have been of type int. But instead, it's of type string. That's not valid."
Or delete the | String s -> s line, and you'll see an error "This expression was expected to have type int but here has type bool." Same thing: each function can have only one return type. If you want to return multiple different possible types from a function, that's what Discriminated Unions are for.
For more reading on F# types, see http://fsharpforfunandprofit.com/series/understanding-fsharp-types.html.
You can wrap all of the expressions into an Option type like Some or String:
let checkType (e:Expr) =
match e with
| String e -> "we are string: " + string e
| Integer e-> "we are integer: " + string e
| Boolean e -> "we are boolean: " + string e

Type 'Double' does not conform to protocol 'Sequence Type'

This is my code and I don't know why it's not working. The title is what the error says. I'm working with Swift in Xcode and the code is supposed to create a function with as many parameters as I tell it to have/unlimited.
func addMyAccountBalances(balances : Double) -> Double {
var result : Double = 0
for balance in balances {
result += balance
}
}
the code is supposed to create a function with as many parameters as i tell it
What you probably want is a function taking a variable number of arguments,
this is indicated by ... following the type:
func addMyAccountBalances(balances : Double ...) -> Double {
var result : Double = 0
for balance in balances {
result += balance
}
return result
}
print(addMyAccountBalances(1.0, 2.0, 3.0))
print(addMyAccountBalances(4.5, 5.6))
Inside the function, balances has the array type [Double] so that
you can iterate over its elements.
Note that this can be written more compactly with reduce():
func addMyAccountBalances(balances : Double ...) -> Double {
let result = balances.reduce(0.0, combine: +)
return result
}
Your code does not compile because balances : Double is just
a double number, not an array or sequence.

Why Scala's foldLeft has lower performance than iterating with an index on strings?

I am comparing the performance of two atoi implementations. The first is iterating on the input string getting chars using charAt; the second is using foldLeft.
object Atoi {
def withRandomAccess(str: String, baze: Int): Int = {
def process(acc: Int, place: Int, str: String, index: Int): Int =
if (index >= 0) process(acc + value(str.charAt(index)) * place, place * baze, str, index-1) else acc
process(0, 1, str, str.length - 1)
}
def withFoldLeft(str: String, base: Int): Int = (0/:str) (_ * base + value(_))
def value(c: Char): Int = { /* omitted for clarity */ }
def symbol(i: Int): Char = { /* omitted for clarity */ }
}
The foldLeft version is 2x to 4x slower (the complete benchmark code is here). I didn't expect this. Do you know why? Is Scala converting the string to a List before processing it? Do you have a hint on how to boost foldLeft performance on strings?
The issue is nothing to do with inlining, it is to do with the boxing/unboxing of Chars that is taking place when you use the foldLeft.
You get foldLeft on String by an implicit conversion to a StringOps, which is not specialized. Each char in the String has to be boxed into a java.lang.Character in order to be passed into the Function2 (argument to foldLeft), then unboxed (much cheaper) to be passed into the value method within the function body, then boxed again to be fed into the next iteration of the fold.
The boxing involves the overhead of creating objects and subsequently garbage-collecting them.
In terms of avoiding boxing, there follows a brief and important point:
you shouldn't attempt to avoid boxing, with a probability of almost 1.
(That is to say, unless you have identified a specific and unacceptable performance degradation which can be attributed to boxing, then you should not worry about it.)
If you are sure that there is an issue which you need to address, avoid the collections and for-comprehensions (which use foreach and flatMap under hood). If you are using a loop, use while.

Resources