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_Last
Error 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.
1 Like
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.Map
module which sholud make this fairly easy. To target DAML-LF 1.11, you need to pass --target=1.11
to daml build
or add build-options: ["--target=1.11"]
to your daml.yaml
.
Now, if you need an integer for another reason, you can, as you already noticed, derive the Enum
typeclass. 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 apply fromEnum
everywhere you need an Int
.
fromEnum : Enum a => a -> Int
toEnum : Enum a => Int -> a
3 Likes
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?
1 Like
DA.Map
is only available in the latest LF version (which is still a preview in SDK 1.9) where we added a new Map
primitive type with arbitrary key types. Older LF versions only provide a map indexed by Text
s. DA.Next.Map
wraps the text map provided you define how the type should be converted to and from Text
in the MapKey
instance. SDK 1.10 will deprecate DA.Next.Map
in favor of DA.Map
.
2 Likes