Using Enum as an integer?
- mlyczakOP 1
I would like to use values defined inside an Enum as integers. These could be:
- used as values when needed
- index e.g. an array
Is it possible in Daml?
I seem not to be able to do that. E.g. I’m getting a parse error on the line:
assert $ length myArray == Unused_LastError wording:
Couldn't match expected type ‘Int’ with actual type ‘SkipassReductionType’Here is my Enum type:
data SkipassReductionType = NoReduction | Youth | Child | Senior | Other | Unused_Last deriving (Eq, Show, Enum)Thank you for any hints.
- cocreature 3
Hi @mlyczak ,
First, I think it’s worth noting that DAML has only provides linked lists not arrays. Given the linear index time on lists, you are often better off, using maps instead of lists and at that point, you can use the enum type directly as the key type. DAML-LF 1.11 which was released as a preview version in SDK 1.9 includes a
DA.Mapmodule which sholud make this fairly easy. To target DAML-LF 1.11, you need to pass--target=1.11todaml buildor addbuild-options: ["--target=1.11"]to yourdaml.yaml.Now, if you need an integer for another reason, you can, as you already noticed, derive the
Enumtypeclass. This provides you with two methods which you can use to convert back and forth. There are no implicit conversion in DAML, so you have to applyfromEnumeverywhere you need anInt.fromEnum : Enum a => a -> Int toEnum : Enum a => Int -> a - mlyczak 1
Thank you @cocreature. This was very helpful.
Is there a difference between DA.Next.Map and DA.Map? I seem to get pointed in the docs to the former. When should I use the latter? - cocreature 2
DA.Mapis only available in the latest LF version (which is still a preview in SDK 1.9) where we added a newMapprimitive type with arbitrary key types. Older LF versions only provide a map indexed byTexts.DA.Next.Mapwraps the text map provided you define how the type should be converted to and fromTextin theMapKeyinstance. SDK 1.10 will deprecateDA.Next.Mapin favor ofDA.Map.