Returning a string from a Function (VAX PASCAL) - pascal

This is one for the software archaeologists!
And before you ask why was I even bothering to try to get this to work the reason it is simply because I can - which I think is a perfectly good excuse!
I found that the following code for a procedure compiles using VAX PASCAL (and runs as expected)..
PROCEDURE format(number : INTEGER);
VAR
result : STRING(16);
BEGIN
:
:
writeln(result);
END.
However if turn this into a function and try to return the result as a string it won't compile.
FUNCTION format(number : INTEGER) : STRING(16);
VAR
result : STRING(16);
BEGIN
:
:
format := result;
END.
The error suggests that the error is at type definition for the function.
FUNCTION format(number : INTEGER) : STRING(16);
1
PASCAL-E-TYPCNTDISCR, Type can not be discriminated in this context
I tried using VARYING and ARRAY types instead of STRING but they don't work either. Unfortunately I can't find an example of a function that returns a STRING in SYS$EXAMPLES or in the manuals I found of bitsavers.
Hopefully someone has a better memory than me.
Thanks

"Pascal's type system has been described as "too strong", because the size of an array or string is part of its type, ..." Strong and weak typing
This gives a hint that the String(16) in the function return value is too vague for the compiler.
Fix that by declaring a string type that suits the compiler:
type
String16 = packed array[1..16] of char;
Then you can use that distinct type in the function:
FUNCTION format(number : INTEGER) : String16;
VAR
result : String16;
BEGIN
:
:
format := result;
END.
This is very much what was used in many early implementations of the pascal language (and Turbo Pascal), and is still valid. Modern compilers, like Delphi and FreePascal, has implemented a specialized dynamic array for strings, which covers a more convenient handling of the string type, not depending on declaring a strict size.

Related

How to have multiple (alternate) return types in Nim?

I can declare a proc to return a "union type", but cannot actually return values of more than one type:
proc test(b: bool) : int|string =
if b: 1 else: "hello"
echo test true
echo test false
Expected:
1
hello
Actual:
Error: type mismatch: got 'string' for '"hello"' but expected 'int literal(1)'
Even if I swap the return types (string|int) the error is the same. I am only allowed to return an int. I tried putting the return type in parens; and I tried using or instead of |. No dice.
What am I missing? (I don't want to use a variant object.)
The code can be tested online at the Nim Playground. I've scoured google and the Nim documentation, and come up empty.
Return types have to be known at compile time in Nim. Imagine you tried to return the result of that procedure to a string variable. Now you're in a scenario where one return value works, but the other would be a compilation error. In order to allow Nim to figure out whether to throw an error or not it must be able to figure out which type will be returned at compile time. The solution here is to use a static[bool] and a when in place of the if. If you actually need a type that can hold different types on runtime you have to use variant objects.

Power Query Type Definition

In Power Query (M) I've found 2 ways to declare types: myVar as type or type text
Each seems to apply to different contexts. For example:
Table.AddColumn(myTable, "NewName", each [aColumn], type text)
or
MyFunc = (aParam as any) as date => Date.From(aParam)
However, this doesn't work as I expect for more complex types, like {text} or {number}, which would be a list of only text values or only numbers. I can use these types with the type syntax, but not the as type syntax.
Why/not?
Also, does declaring types in M have any performance impact, or is it just to raise an error if an incorrect type is passed/returned?
Declaring types in "M" should normally have very little performance impact, and will make your functions more "self-documenting".
When a function is invoked, the function arguments type "kind" is checked, and not the custom, full type definition. So passing a list of numbers to a function that expects list-of-text doesn't cause any errors. You can see that with some "M":
let
FunctionType = type function (l as { text }) as any,
UntypedFunction = (l) => l{0},
TypedFunction = Value.ReplaceType(UntypedFunction, FunctionType),
Invoked = TypedFunction({0, 1, 2})
in
Invoked
Not checking the recursive type is good for performance because checking each element of a list would require looping through the whole list.
When you write a function value like (l) => l{0} you can only use primitive types like as list and not as { text }. I think this limitation is intended to guide the function author into not putting type restrictions that won't be honored by the function.
You can read more about what the syntax allows in the Language Specification. (If that link dies you should be able to follow the PDF link from MDSN.)

Modelsim / reading a signal value

In my simulation, I want to have RW access to signals whereever there are in the project. To get the write access, I use the "signal_force" procedure from the modelsim_lib library. But to get the read access I havn't find the corresponding function.
The reason why signal_force fit my needs is that I'm working with input text files, so I have the name and the value of the signal from a "string" or a "line" variable and I can directly give these variable to the fonction.
I cannot use the "init_signal_spy" procedure because this procedure doesn't give back a value into a string but just duplicates the behavior of a signal onto an other. As my project has to be as generic as possible, I work with variables declared into procedures and I cannot link a signal onto a variable.
Thanks for your help
edited
Sorry, I win the "did not read very carefully" award for the day...
Just for completeness, I'm leaving the part of my answer that deals with signal spy (which is a proprietary ModelSim method), even though you said it wouldn't work for you:
library modelsim_lib;
use modelsim_lib.util.all;
architecture ...
signal local_sig ...
begin
process
begin
init_signal_spy("/sim/path/to/signal/internal_sig", "local_sig");
With VHDL-2008 (if you have support for it), the standard way to access signals not in scope is hierarchical/external names, and as a bonus, it does both "write" and "read". I may be a bit rusty on the nuances, but you access them like:
<<signal .sim.path.to.signal.internal_sig : std_logic>>
And you should be able to use that in place of any normal in-scope identifier, I believe. Aliases, assignments, etc.
If you're comfortable writing C code it should be straightforward to achieve what you want using the VHPI, although sadly despite being part of the VHDL standard Mentor are not planning to implement it. However it will also be possible using FLI although you're locked into a proprietary interface.
Something like this:
procedure get_signal_value_as_string(
vhdl_path : IN string;
vhdl_value: OUT string);
attribute FOREIGN of get_signal_value_as_string : procedure is “my_func mylib.so”;
procedure get_signal_value_as_string(
vhdl_path : IN string;
vhdl_value: OUT string) is
begin
report “ERROR: foreign subprogram get_signal_value_as_string not called”;
end;
Then in C:
#include <stdio.h>
#include "mti.h"
/* Convert a VHDL String array into a NULL terminated string */
static char *get_string(mtiVariableIdT id)
{
static char buf[1000];
mtiTypeIdT type;
int len;
mti_GetArrayVarValue(id, buf);
type = mti_GetVarType(id);
len = mti_TickLength(type);
buf[len] = 0;
return buf;
}
void my_func (
mtiVariableIdT vhdl_path /* IN string */
mtiVariableIdT vhdl_value /* OUT string */
)
{
mtiSignalIdT sigID = mti_FindSignal(get_string(vhdl_path));
mtiInt32T value = mti_GetSignalValue(sigID);
...
}
Plenty of example code in the FLI manual.

Why does using Linq's .Select() return IEnumerable<dynamic> even though the type is clearly defined?

I'm using Dapper to return dynamic objects and sometimes mapping them manually. Everything's working fine, but I was wondering what the laws of casting were and why the following examples hold true.
(for these examples I used 'StringBuilder' as my known type, though it is usually something like 'Product')
Example1: Why does this return an IEnumerable<dynamic> even though 'makeStringBuilder' clearly returns a StringBuilder object?
Example2: Why does this build, but 'Example1' wouldn't if it was IEnumerable<StringBuilder>?
Example3: Same question as Example2?
private void test()
{
List<dynamic> dynamicObjects = {Some list of dynamic objects};
IEnumerable<dynamic> example1 = dynamicObjects.Select(s => makeStringBuilder(s));
IEnumerable<StringBuilder> example2 = dynamicObjects.Select(s => (StringBuilder)makeStringBuilder(s));
IEnumerable<StringBuilder> example3 = dynamicObjects.Select(s => makeStringBuilder(s)).Cast<StringBuilder>();
}
private StringBuilder makeStringBuilder(dynamic s)
{
return new StringBuilder(s);
}
With the above examples, is there a recommended way of handling this? and does casting like this hurt performance? Thanks!
When you use dynamic, even as a parameter, the entire expression is handled via dynamic binding and will result in being "dynamic" at compile time (since it's based on its run-time type). This is covered in 7.2.2 of the C# spec:
However, if an expression is a dynamic expression (i.e. has the type dynamic) this indicates that any binding that it participates in should be based on its run-time type (i.e. the actual type of the object it denotes at run-time) rather than the type it has at compile-time. The binding of such an operation is therefore deferred until the time where the operation is to be executed during the running of the program. This is referred to as dynamic binding.
In your case, using the cast will safely convert this to an IEnumerable<StringBuilder>, and should have very little impact on performance. The example2 version is very slightly more efficient than the example3 version, but both have very little overhead when used in this way.
While I can't speak very well to the "why", I think you should be able to write example1 as:
IEnumerable<StringBuilder> example1 = dynamicObjects.Select<dynamic, StringBuilder>(s => makeStringBuilder(s));
You need to tell the compiler what type the projection should take, though I'm sure someone else can clarify why it can't infer the correct type. But I believe by specifying the projection type, you can avoid having to actually cast, which should yield some performance benefit.

Delphi Interface Performance Issue

I have done some really serious refactoring of my text editor. Now there is much less code, and it is much easier to extend the component. I made rather heavy use of OO design, such as abstract classes and interfaces. However, I have noticed a few losses when it comes to performance. The issue is about reading a very large array of records. It is fast when everything happens inside the same object, but slow when done via an interface. I have made the tinyest program to illustrate the details:
unit Unit3;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs;
const
N = 10000000;
type
TRecord = record
Val1, Val2, Val3, Val4: integer;
end;
TArrayOfRecord = array of TRecord;
IMyInterface = interface
['{C0070757-2376-4A5B-AA4D-CA7EB058501A}']
function GetArray: TArrayOfRecord;
property Arr: TArrayOfRecord read GetArray;
end;
TMyObject = class(TComponent, IMyInterface)
protected
FArr: TArrayOfRecord;
public
procedure InitArr;
function GetArray: TArrayOfRecord;
end;
TForm3 = class(TForm)
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form3: TForm3;
MyObject: TMyObject;
implementation
{$R *.dfm}
procedure TForm3.FormCreate(Sender: TObject);
var
i: Integer;
v1, v2, f: Int64;
MyInterface: IMyInterface;
begin
MyObject := TMyObject.Create(Self);
try
MyObject.InitArr;
if not MyObject.GetInterface(IMyInterface, MyInterface) then
raise Exception.Create('Note to self: Typo in the code');
QueryPerformanceCounter(v1);
// APPROACH 1: NO INTERFACE (FAST!)
// for i := 0 to high(MyObject.FArr) do
// if (MyObject.FArr[i].Val1 < MyObject.FArr[i].Val2) or
// (MyObject.FArr[i].Val3 < MyObject.FArr[i].Val4) then
// Tag := MyObject.FArr[i].Val1 + MyObject.FArr[i].Val2 - MyObject.FArr[i].Val3
// + MyObject.FArr[i].Val4;
// END OF APPROACH 1
// APPROACH 2: WITH INTERFACE (SLOW!)
for i := 0 to high(MyInterface.Arr) do
if (MyInterface.Arr[i].Val1 < MyInterface.Arr[i].Val2) or
(MyInterface.Arr[i].Val3 < MyInterface.Arr[i].Val4) then
Tag := MyInterface.Arr[i].Val1 + MyInterface.Arr[i].Val2 - MyInterface.Arr[i].Val3
+ MyInterface.Arr[i].Val4;
// END OF APPROACH 2
QueryPerformanceCounter(v2);
QueryPerformanceFrequency(f);
ShowMessage(FloatToStr((v2-v1) / f));
finally
MyInterface := nil;
MyObject.Free;
end;
end;
{ TMyObject }
function TMyObject.GetArray: TArrayOfRecord;
begin
result := FArr;
end;
procedure TMyObject.InitArr;
var
i: Integer;
begin
SetLength(FArr, N);
for i := 0 to N - 1 do
with FArr[i] do
begin
Val1 := Random(high(integer));
Val2 := Random(high(integer));
Val3 := Random(high(integer));
Val4 := Random(high(integer));
end;
end;
end.
When I read the data directly, I get times like 0.14 seconds. But when I go through the interface, it takes 1.06 seconds.
Is there no way to achieve the same performance as before with this new design?
I should mention that I tried to set PArrayOfRecord = ^TArrayOfRecord and redefined IMyInterface.arr: PArrayOfRecord and wrote Arr^ etc in the for loop. This helped a lot; I then got 0.22 seconds. But it is still not good enough. And what makes it so slow to begin with?
Simply assign the array to a local variable before iterating through the elements.
What you're seeing is that the interface methods calls are virtual and have to be called through an indirection. Also, the code has to pass-through a "thunk" that fixes up the "Self" reference to now point to the object instance and not the interface instance.
By making only one virtual method call to get the dynamic array, you can eliminate that overhead from the loop. Now your loop can go through the array items without the extra overhead of the virtual interface method calls.
You're comparing oranges with apples, as the first test reads a field (FArr), while the second test reads a property (Arr) that has a getter assigned with it. Alas, interfaces offer no direct access to their fields, so you really can't do it any other way than like you did.
But as Allen said, this causes a call to the getter method (GetArray), which is classified as 'virtual' without you even writing that because it's part of an interface.
Thus, every access results in a VMT-lookup (indirected via the interface) and a method call.
Also, the fact that you're using a dynamic array means that both the caller and the callee will do a lot of reference-counting (you can see this if you take a look at the generated assembly code).
All this is already enough reasons to explain the measured speed difference, but can indeed easily be overcome using a local variable and read the array only once. When you do that, the call to the getter (and all the ensueing reference counting) is taking place only once. Compared to the rest of the test, this 'overhead' becomes unmeasurable.
But note, that once you go this route, you'll loose encapsulation and any change to the contents of the array will NOT reflect back into the interface, as arrays have copy-on-write behaviour. Just a warning.
Patrick and Allen's answers are both perfectly correct.
However, since your question talks about improved OO design, I feel a particular change in your design that would also improve performance is appropriate to discuss.
Your code to set the Tag is "very controlling". What I mean by this is that you're spending a lot of time "poking around inside another object" (via an interface) in order to calculate your Tag value. This is actually what exposed the "performance problem with interfaces".
Yes, you can simply deference the interface once to a local variable, and get a massive improvement in performance, but you'll still be poking around inside another object. One of the important goals in OO design is to not poke around where you don't belong. This actually violates the Law of Demeter.
Consider the following change which empowers the interface to do more work.
IMyInterface = interface
['{C0070757-2376-4A5B-AA4D-CA7EB058501A}']
function GetArray: TArrayOfRecord;
function GetTagValue: Integer; //<-- Add and implement this
property Arr: TArrayOfRecord read GetArray;
end;
function TMyObject.GetTagValue: Integer;
var
I: Integer;
begin
for i := 0 to High(FArr) do
if (FArr[i].Val1 < FArr[i].Val2) or
(FArr[i].Val3 < FArr[i].Val4) then
begin
Result := FArr[i].Val1 + FArr[i].Val2 -
FArr[i].Val3 + FArr[i].Val4;
end;
end;
Then inside TForm3.FormCreate, //APPROACH 3 becomes:
Tag := MyInterface.GetTagValue;
This will be as fast as Allen's suggestion, and will be a better design.
Yes, I'm fully aware you simply whipped up a quick example to illustrate the performance overhead of repeatedly looking something up via interface. But the point is that if you have code performing sub-optimally because of excessive accesses via interfaces - then you have a code smell that suggests you should consider moving the responsibility for certain work into a different class. In your example TForm3 was highly inappropriate considering everything required for the calculation belonged to TMyObject.
your design use huge memory. Optimize your interface.
IMyInterface = interface
['{C0070757-2376-4A5B-AA4D-CA7EB058501A}']
function GetCount:Integer:
function GetRecord(const Index:Integer):TRecord;
property Record[Index:Integer]:TRecord read GetRecord;
end;

Resources