how to use function in systemverilog? - system-verilog

I found sentencenlike this.
function device check_device ;
case ..
in system verilog code.
The device are consist of enum typedef.
Also check _device is nothing.
Does anyone know what is it? Could you please explain this?
Also Why does -> event exist except #?
What are different between them?

Given the code snippet, check_device is the name of the function you are defining. It would return a value of type device, which as you said is typedefed as an enum definition.
In SystemVerilog, you can declare an explicit event and wait on that. The operator -> is used to trigger an explicit event. Operator #, as in Verilog, is there to let you wait for an event.
For example:
class Foo;
event bar;
// ...
function void notify_bar;
->bar;
endfunction;
task wait_for_bar;
#bar;
endtask;
endclass

Related

How can define enumerator in Methods?

There is a problem when u define an enum in a method.
I was trying to do this:
VAR
enumA:(A,B,C);
END_VAR
and there is the compiler reaction when I used this in TwinCAT3 Shell (TcXaeShell).
any help would be appreciated.
You can only use global enumerations in methods. It's one of the limitations with local enumerations.
https://alltwincat.com/2021/11/16/local-enumerations/
You should first define variable type as enumeration in DUT
TYPE MyEnum:
(A, B, C)
END_TYPE
Then in a program you can declare variable of that type
VAR
enum: MyEnum;
END_VAR
Inside the program if you want to compare it.
IF enum = MyEnum.C THEN
// Do something
END_IF;
I’ve run into this issue before. You must declare the local enumeration in the variables section of the function block. Then you can use it in the methods of the function block.

Swift generics: How to represent 'no type'?

I am using Google's promises library, and I would like to create promise without any type (because I don't need any).
However, I am being forced to pick some type:
let promise = Promise<SomeType>.pending()
Is there a type I could pass in place of SomeType that would essentialy mean 'no type', when I need promises just for async flow and exception catching, but I don't want to return a specific value from a function?
For example, some type whose only valid value is nil?
I have encountered this problem in multiple places, the only workaround I found so far is to always provide a non-generic alternative, but it gets really tedious and leads to duplicate code.
Types are sets of values, like Int is the set of all integer numbers, String is the set of all sequences of characters and so on.
If you consider the number of items in the set, there are some special types with 0 items and 1 items exactly, and are useful in special cases like this.
Never is the type with no values in it. No instance of a Never type can be constructed because there are no values that it can be (just like an enum with no cases). That is useful to mark situations, code flow etc as 'can't happen', for example the compiler can know that a function that returns Never, can never return. Or that a function that takes Never can never be called. A function that returns Result<Int, Never> will never fail, but is in the world of functions returning Result types. But because never can't be constructed it isn't what you want here. It would mean a Promise that can't be fulfilled.
Void is the type with exactly 1 value. It's normally spelled () on the left and Void on the right, of a function definition. The value of a void is not interesting. It's useful to make a function that returns Void because those are like what other languages call subroutines or procedures. In this case it means a Promise that can be fulfilled but not with any value. It can only be useful for its side effects, therefore.
Is it a correct solution or a workaround if we create an empty class
class Default_Class : Codable {
}
and use this as Promise<Default_Class>.pending

Why can't I declare a variable or function more than once with different types?

Okay I know "One Definition Rule", but when I try to declare a variable with different types subsequently in source code, I run into some mistake like following:
int fkc();
void fkc();
enter image description here
I mean these two statements are just two declarations, not definitions. Alright, Does every declaration have to have only one unique definition?
In C++, you can't overload functions based on return type.
Overload resolution takes into account the function name , cv-qualifiers , the number of parameters and their types.
You could do something like:
auto fck()
{
if constexpr(...) return my_int;
else /* do smth without return */
}
but that's not function overloading of course.
Because you cannot overload the method just by changing return type . It is not allowed. The compiler distinguishes function invocations based on signature.and the signature of function includes only function name and arugments like
func(int x....) which does not include return type

I can't figure out how this switch statement is working?

func performMathAverage (mathFunc: String) -> ([Int]) -> Double {
switch mathFunc {
case "mean":
return mean
case "median":
return median
default:
return mode
}
}
I got this example from a swift learning book and its speaking of the topic of returning function types and this is just a part of the whole program I didn't want to copy and paste it all. My confusion is that the book says:
"Notice in performMathAverage , inside the switch cases, we return
either mean , median , or mode , and not mean() , median() , or mode()
. This is because we are not calling the methods, rather we are
returning a reference to it, much like function pointers in C. When
the function is actually called to get a value you add the parentheses
suffixed to the function name. Notice, too, that any of the average
functions could be called independently without the use of the
performMathAverage function. This is because mean , median , and mode
are called global functions ."
The main question is: "Why are we not calling the methods?"
and what do they mean we are returning a reference to it??
What do they mean by reference? Im just confused on this part.
You stated your main question as:
"Why are we not calling the methods?" and what do they mean we are returning a reference to it??
This is a little tricky to grasp at first, but what it's saying is that we don't want the result of the function, we want the function itself.
Sometimes things like this are easier to understand w/ a type alias:
Starting w/ [Int] -> Int, what we're saying there is "a function that takes an array of Ints and returns a single Int"
Let's make a type alias for clarity:
typealias AverageFunction = [Int] -> Int
Now our function (from your example) looks like this:
func performMathAverage(mathFunc: String) -> AverageFunction {
Although, the naming conventions here are pretty confusing since we're not performing anything, instead let's call it like this:
func getAverageFunctionWithIdentifier(identifier: String) -> AverageFunction {
Now it's very clear that this method is functioning like a factory that returns us an average function based on the identifier we provide. Now let's look at the implementation:
func getAverageFunctionWithIdentifier(identifier: String) -> AverageFunction {
switch identifier {
case "mean":
return mean
case "median":
return median
default:
return mode
}
}
So now, we're running a switch on the identifier to find the corresponding function. Again, we're not calling the function because we don't want the value, we want the function itself. Let's look at how we would call this:
let averageFunction = getAverageFunctionWithIdentifier("mean")
Now, averageFunction is a reference to the mean function which means we can use it to get the mean on an array of integers:
let mean = averageFunction([1,2,3,4,5])
But what if we wanted to use a different type of average, say median? We wouldn't have to change anything except for the identifier:
let averageFunction = getAverageFunctionWithIdentifier("median")
let median = averageFunction([1,2,3,4,5])
This example is pretty contrived, but the benefits of this is that by abstracting a function out to it's type (in this case [Int] -> Int, we can use any function that conforms to that type interchangeably.
This is functional programming!
This has to do with the functional programming aspects of swift. Here functions are treated like first class citizens meaning you can treat them like variables.
Why are we not calling the methods?
You are not calling the methods, because you have no argument to apply. The point of the function is to determine which function you would like to use. Of course the name of the function is terrible and does not accurately represent what the function does. It should be more like func determineMathFuncToUse, then you could use it like
var myFunc = determineMathFuncToUse("median")
// Now, you would be able to use myFunc just like you would use median
// e.g. myFunc(some_array) == median(some_array)
This is pretty easy to understand. In Swift you can store references to functions (the closest you can achieve in Objective-C is the reference to block).
func performMathAverage (mathFunc: String) -> ([Int]) -> Double
This is the function whose return type is:
([Int]) -> Double
As you can see the return type of this function is a function which accepts an array of Int and returns Double.
And in code you see that it returns one of three functions: mean, mode, and median. Each of these functions accepts an array of Int and returns Double.
Due to this code below:
let meanFunc = performMathAverage("mean")
let mean = meanFunc(someIntArray)
is identical to:
let mean = mean(someIntArray)
I hope this helps.
The reason why functions are NOT executed in code is because this example illustrates how you can STORE reference to functions.
It might be difficult to understand why you would want to do it in this particular case, but, hey, printing "Hello world" also seems meaningless :)
You are referring to an example in a tutorial so it is not strange that they are oversimplifying things. However, believe me, that in a real world there are many cases in which storing references to functions is very-very useful!
One obvious example is when you want to store reference to some completion handler which you want to execute at the end of some lengthy operation. And which can be different depending on the context from which you initiated this operation.
To answer your question, you are effectively returning the function itself, and not the result of calling that function. In this case, it lets you choose a function (using the switch statement) and evaluate it later. A helpful way to think about it is that functions are also a type of variable, and you can pass them around as well as evaluate them.
As a general stylistic thing, it's good practice to end each case with a break. It makes no difference here because return will also end the execution of the function, but without a break, all code after the correct case will be executed, not just the code within the correct case. Running into another case statement doesn't break out of the switch statement by itself.
Why are we not calling the methods?
Presumably, the method will be called later. The purpose of the switch statement is to return a function that can be used later.
What do they mean we are returning a reference to it? ... What do they mean by reference?
The "reference" language is a bit confusing - functions are reference types, but that isn't super important to what is going on. You can think of it as just returning a function.
The bottom line is that functions in swift can be used like any other type - they can be stored in variable or constants, they can be passed into a function as a parameter, and they can be returned from a function.
In this case, you have a function that is designed to return a function. If you want to obtain the mean, you pass the string "mean" and the function will return a new function that will obtain the mean when you call it.

What's the proper way to declare a field holding a function in dart?

Imagine a silly class like this:
class ConditionalWorker{
var validityChecker= (inputs)=>true;
ConditionalWorker(this.validityChecker)
...
Now my question is, what is the proper way of declaring the validityChecker field?
This tutorial suggests using typedefs. But that's not very practical. Firstly it's a chore to write a lot of typedefs that would only be used once. And secondly these typedefs show up and pollute the autocompletion of my IDE.
The var works best, with custom setters/constructor arguments to keep it always of a specific kind, but I know it's discouraged by the style guide.
I could do Function<bool> but that just a more glorified var and the amount of work is the same.
It's a shame because it's perfectly legal to have a function like this:
bool every(bool test(E element));
where the parameter is a very well defined function, but I can't have a field declared the same way:
bool test(E element);
But hopefully there is something just as good that I didn't figure out. Right?d
If you want a function type more specific than Function, you need a typedef.
If you don't like to have named typedefs for every return type, you can define generic function types yourself.
typedef R function0<R>();
typedef R function1<S,R>(S arg1);
typedef R function2<S,T,R>(S arg1. T arg2);
typedef R function3<S,T,U,R>(S arg1, T arg2, U arg3);
Then you can write:
function1<int,int> curryAdd(int x) => (int y) => x + y;
Or if function0 looks bad to you, you can name them NullaryFunction, UnaryFuncytion, BinaryFunction, TernaryFunction, or any other name that you like.
If Function<bool> is not specific enough (you also want to specify the number and type of the arguments you have to use typedefs. There are no other ways.
I'm not sure why you think it is not practical. If you want to specify the type for a field that references a value you have to use one of the existing classes or create a new one. It's the same for fields referencing functions.
With Dart 2 we can use inline function types and we need to use it instead of typedefs where possible.
With inline function types we now can define a function as a field or a property as simple as this:
final bool Function(E) test;