Constant with all items of an enum in Delphi - delphi

Is it possible to have a constant set of all items of an enumerated type in Delphi?
type
TItems = (
iOne,
iTwo,
iThree
);
TItemsSet = set of TItems;
const
SOMEITEMS: TItemsSet = [iTwo, iThree];
ALLITEMS: TItemsSet = ?????
I would like ALLITEMS to always hold all members of TItems. And I would prefer to have this as constant.
Edited:
And what, if my enum looks like this:
TItems = (
iOne = 1,
iTwo = 2,
iThree = 5
);

(From the comments)
[Low(T)..High(T)] works for any type T that is small enough to be used as a set, to include all items that can be included in the set.
As noted in the comments, this is enough for the enumeration in the question, but in general, may include constants that aren't defined as part of the enumeration.

Related

what's the difference between using List.from() and List.of() in Dart laungage [duplicate]

In Dart, what's the difference between List.from and List.of, and between Map.from and Map.of? Their documentation is not totally clear:
/**
* Creates a [LinkedHashMap] instance that contains all key/value pairs of
* [other].
*
* The keys must all be instances of [K] and the values of [V].
* The [other] map itself can have any type.
*
* A `LinkedHashMap` requires the keys to implement compatible
* `operator==` and `hashCode`, and it allows `null` as a key.
* It iterates in key insertion order.
*/
factory Map.from(Map other) = LinkedHashMap<K, V>.from;
/**
* Creates a [LinkedHashMap] with the same keys and values as [other].
*
* A `LinkedHashMap` requires the keys to implement compatible
* `operator==` and `hashCode`, and it allows `null` as a key.
* It iterates in key insertion order.
*/
factory Map.of(Map<K, V> other) = LinkedHashMap<K, V>.of;
/**
* Creates a list containing all [elements].
*
* The [Iterator] of [elements] provides the order of the elements.
*
* All the [elements] should be instances of [E].
* The `elements` iterable itself may have any element type, so this
* constructor can be used to down-cast a `List`, for example as:
* ```dart
* List<SuperType> superList = ...;
* List<SubType> subList =
* new List<SubType>.from(superList.whereType<SubType>());
* ```
*
* This constructor creates a growable list when [growable] is true;
* otherwise, it returns a fixed-length list.
*/
external factory List.from(Iterable elements, {bool growable: true});
/**
* Creates a list from [elements].
*
* The [Iterator] of [elements] provides the order of the elements.
*
* This constructor creates a growable list when [growable] is true;
* otherwise, it returns a fixed-length list.
*/
factory List.of(Iterable<E> elements, {bool growable: true}) =>
new List<E>.from(elements, growable: growable);
Is the difference related to generics? Maybe the .from factories let you change the type of the list, while the .of ones do not? I come from a Java background, which works with type erasure, and maybe types are reified in Dart and you cannot use casts or raw types to change list/map types?
The important difference between the from and of methods are that the latter have type annotations and the former do not. Since Dart generics are reified and Dart 2 is strongly typed, this is key to both ensuring the List/Map is correctly constructed:
List<String> foo = new List.from(<int>[1, 2, 3]); // okay until runtime.
List<String> bar = new List.of(<int>[1, 2, 3]); // analysis error
And ensuring that the types are inferred correctly:
var foo = new List.from(<int>[1, 2, 3]); // List<dynamic>
var bar = new List.of(<int>[1, 2, 3]); // List<int>
In Dart 1 types were completely optional, so many APIs were untyped or partially typed. List.from and Map.from are good examples, since the Iterable/Map passed into them doesn't have a type parameter. Sometimes Dart can figure out what the type of this object should be, but sometimes it just ended up as List<dynamic> or Map<dynamic, dynamic>.
In Dart 2 the type dynamic was changed from being both a top (Object) and bottom (null) type to only being a top type. Thus if you created a List<dynamic> accidentally in Dart 1 you could still pass it to a method which required a List<String>. But in Dart 2 List<dynamic> is almost the same as List<Object>, so this would fail.
If you are using Dart 2, you should always use the typed version of these APIs. Why do the old ones still exist, and what are the plans there? I don't really know. I would guess they would be phased out over time, along with the rest of the Dart 1.
Whenever possible it is better to use collection literals now rather than the .from or .of constructors. Apparently there are some performance benefits to this. (See link at bottom.)
Examples:
something.toList()
[...something]
Exception:
Can use .from if you need to downcast.
If you do use them, though, you should always include the type.
Source: Dart team engineer's post
List.of() and toList()
They are used to create a new list of the same type as the original, but List.of() can be used to upcast:
var ints = <int> [0];
var newList1 = ints.toList(); // List<int>
var newList2 = List<num>.of(ints); // List<num>
You can also copy a list by doing:
var newList3 = [...ints]; // List<int>
var newList4 = [for (var v in ints) v]; // List<int>
List.from()
Use this if you want to downcast and therefore it is important that the subtype is a type of supertype.
var ints = List<int>.from(<num>[0, 1]); // Good as all elements are of type `int`
var ints = List<int>.from(<num>[0, 1.5]); // Bad as some elements are of type `double`

Is it possible to make a TreeMap from a Map literal?

I have a Map literal, an I want it to be a TreeMap, but by default I believe it's a LinkedHashMap. Casting a LinkedHashMap to a TreeMap won't work as it's not a subtype.
Basically, I'm looking for the simplest way to make this work:
var map = <int, int>{for(int i = 0; i < intervals.length; i++) intervals[i][0] : i} as SplayTreeMap;
As mentioned before, casting as SplayTreeMap won't work as they types don't align.
Thanks much in advance
Use the SplayTreeMap.from constructor to create a SplayTreeMap. There isn't any way to cast it as you said.
Remove the as from your current code and add this to get your SplayTreeMap:
var newMap = SplayTreeMap.from(map);
Depending on your key type and your use case, you can pass compare and isValidKey parameters as well. Full constructor definition:
SplayTreeMap<K, V>.from(
Map other,
[int compare(
K key1,
K key2
),
bool isValidKey(
dynamic potentialKey
)]
)

How I know the index of specific value in a set

I have these codes:
TAPPUGroup = (APP_UG_USERS, APP_UG_SUPER_USERS, APP_UG_ADMINS);
TAPPUGroups = set of TAPPUGroup;
TAppUser = record
UID: integer;
UName: string;
UGroup: TAPPUGROUPS;
end;
...
LoggedUser: TAppUser;
I used include to add groups to LoggedUser.UGroup, now how I know the index of specific value in TAPPUGroup for example if APP_UG_SUPER_USERS included in LoggedUser.UGroup how I can get it's index in TAPPUGroup ?
Example: If LoggedUser.UGroup = APP_UG_SUPER_USERS then I want to return 1 if LoggedUser.UGroup = APP_UG_ADMINS I want to return 2 and so on.
If you really do want the index of a given enumeration item in the enumeration, all you need to do is just use Ord().
To go the other way, you can use the enumeration name as it it were a function:
AGroup := TAPPUGroup(1);
Anyway, Ord() is how you find the index of a given enumeration value (like APP_UG_USERS) in a contiguous enumeration declaration. To find out whether a particular set instance contains a given set element, ou use the "if xxx in ..." construct Remy shows, e.g.
if APP_UG_USERS in MySet then ...
You can also do this
var
AValue : TAPPUGroup;
MySet : TAPPUGroups ;
for AValue:= Low(TAPPUGroup) to High(TAPPUGroup) do
if AValue in MySet then ...
You don't need the index. To know if a value exists in the Set, use the in operator instead:
if APP_UG_SUPER_USERS in LoggedUser.UGroup then

Absolute addressing fields in a record type [duplicate]

This question already has answers here:
How do I translate a C union into Delphi?
(2 answers)
Closed 7 years ago.
I am attempting to interface with an embedded system that transmits and receives data with a fairly simple format but has strict sizing requirements.
In C, you would use a union type to expose some variable data with potentially different types located at the same spot in memory. Add a variable of this union type to a struct, and then you can (carefully) refer to that struct field with various names and types:
for simplicity, please ignore byte alignment and packing
typedef enum { F1_V1, F1_V2, F1_V3 } FLAG_1_T;
typedef enum { F2_V1, F2_V1 } FLAG_2_T;
typedef union
{
FLAG_1_T flag_1;
FLAG_2_T flag_2;
}
FLAG_T;
typedef struct
{
BYTE_T id;
INT32_T value;
FLAG_T flag;
}
DATA_ITEM_T;
So now I can interpret the flag field as either FLAG_1_T or FLAG_2_T.
I would like to use this same sort of approach in Delphi 2010. I've tried to accomplish this by using absolute addressing for fields of a record:
type
FLAG_1_T = ( F1_V1, F1_V2, F1_V3 );
FLAG_2_T = ( F1_V1, F1_V2 );
type
DATA_ITEM_T = record
id : BYTE_T;
value : INT32_T;
flag_1 : FLAG_1_T;
flag_2 : FLAG_2_T absolute flag_1;
end;
But this fails to compile with syntax error E2029 ';' expected but identifier 'absolute' found.
If I bring those flag declarations outside of the record type definition (but at the same scope as the record type def), it compiles fine:
note that this is useless for what I'm trying to accomplish
type
FLAG_1_T = ( F1_V1, F1_V2, F1_V3 );
FLAG_2_T = ( F1_V1, F1_V2 );
type
DATA_ITEM_T = record
id : BYTE_T;
value : INT32_T;
end;
var
flag_1 : FLAG_1_T;
flag_2 : FLAG_2_T absolute flag_1;
So why can't I do this within a record? Is there another way to accomplish this?
You can translate a C union to Delphi using a record type with a variant part:
type
FLAG_T = record
case Boolean of
False: (flag_1: FLAG_1_T);
True: (flag_2: FLAG_2_T);
end;

F# Referencing Types

I am working on a project where the F# code will be consumed by other .NET projects - so I am using classes. I created a code file like this:
namespace StockApplication
open System
type Stock =
{Symbol: String;
DayOpen: Decimal;
Price: Decimal;
}
member x.GetChange () =
x.Price - x.DayOpen
member x.GetPercentChange() =
Math.Round(x.GetChange()/x.DayOpen,4)
This works fine when I consume it from some unit tests written in C#. For example:
[TestMethod]
public void CreateStock_ReturnsValidInstance()
{
Stock stock = new Stock("TEST", 10, 10.25M);
Assert.IsNotNull(stock);
}
I then went to create another file with another class. This class uses the 1st class so I made sure it was below the original class in VS2012. When I created the next class, I can see it available via intellisense.
namespace StockApplication
open System
type StockTicker() =
member x.GetStock () =
StockApplication.Stock
However, every attept to either new it or refer it gives me the same error:
Error 1 The value, constructor, namespace or type 'Stock' is not
defined
Does anyone have any insight on why I can just simply new up a class that I created in F# in another F# file?
Thanks in advance.
Your C# test having Stock stock = new Stock("TEST", 10, 10.25M); that was compiled without a problem prompts to believe that F# constructor for the Stock should look the same. But this is not true and, perhaps, was the source of your confusion.
Your original
type Stock =
{Symbol: String;
DayOpen: Decimal;
Price: Decimal; }
is of F# type Record indeed, not an ordinary class. The following excerpt from MSDN applies:
Record construction also differs from class construction. In a record type, you cannot define a constructor.
Meaning that
let stock = Stock("ABC"; 10M; 10M)
will produce error FS0039: The value or constructor 'Stock' is not defined while
let stock = { Symbol = "ABC"; DayOpen = 10M; Price = 10M; }
will successfully create a record instance.
In order to build an instance of type Stock in your second F# type StockTicker you should use record construction syntax, something like
member x.GetStock () = { Symbol = "MSFT"; DayOpen = 32M; Price = 32.5M; }
which compiles without any problems.
When it comes to interop use of F# record from C# the latter follows the syntax that you applied in your test method.
OK, after digging into this reference (MSDN was 0 help) here, I found the answer.
Here is the syntax for the Stock class:
namespace StockApplication
open System
type Stock = class
val Symbol: String
val DayOpen: Decimal
val Price: Decimal
new (symbol, dayOpen, price) =
{
Symbol = symbol;
DayOpen = dayOpen;
Price = price
}
member x.GetChange () =
x.Price - x.DayOpen
member x.GetPercentChange() =
Math.Round(x.GetChange()/x.DayOpen,4)
end
And here is the syntax for the consuming class:
namespace StockApplication
type StockTicker() =
member x.GetStock () =
let y = new Stock("AET",1m,1m)
y.DayOpen

Resources