Nim: standard way to convert integer/string to enum
Asked Answered
P

1

8

The question is Nim language specific. I am looking for a standard to way to convert integer/string into enum in a type safe way. Converting from enum to integer/string is easy using ord() and $(), but i can't find an easily way to make opposite transformation.

Suppose I have the following type declaration

ProductGroup {.pure.} = enum
  Food = (3, "Food and drinks"),
  kitchen = (9, "Kitchen appliance and cutlery"),
  Bedroom = (15, "Pillows, Beddings and stuff"),
  Bathroom = (17, "Shower gels and shampoo")

I am looking for a standard way to do:

const
   product1 : seq[ProductGroup] = xxSomethingxx(@[3, 3, 17, 9, 15])

   product2 : seq[ProductGroup] = zzSomethingzz(@["Kitchen appliance and cutlery", "Kitchen appliance and cutlery", "Shower gels and shampoo"]) 

   product3 : seq[ProductGroup] = xxSomethingxx(@[2]) ## compilation error "2 does not convert into ProductGroup"
Pedal answered 23/3, 2017 at 13:30 Comment(0)
H
10

Type conversion from int to enum, strutils.parseEnum from string to enum:

import strutils, sequtils

type ProductGroup {.pure.} = enum
  Food = (3, "Food and drinks"),
  kitchen = (9, "Kitchen appliance and cutlery"),
  Bedroom = (15, "Pillows, Beddings and stuff"),
  Bathroom = (17, "Shower gels and shampoo")

const
  product1 = [3, 3, 17, 9, 15].mapIt(ProductGroup(it))
  product2 = ["Kitchen appliance and cutlery", "Kitchen appliance and cutlery", "Shower gels and shampoo"].mapIt(parseEnum[ProductGroup](it))
  product3 = ProductGroup(2)
Hoenack answered 23/3, 2017 at 13:55 Comment(4)
I am using nim 0.16.0 and getting the following if I try to compile: enum.nim(10, 31) template/generic instantiation from here lib\pure\collections\sequtils.nim(626, 29) template/generic instantiation from here lib\system.nim(672, 10) Warning: Cannot prove that 'result' is initialized. This will become a compile time error in the future. [ProveInit] enum.nim(10, 50) Error: type mismatch: got (ProductGroup) but expected 'outType = enum'Pedal
Sounds like a bug in Nim 0.16.0. It works in current devel branch.Hoenack
Thanks, checked with the latest nim. Works as expectedPedal
What worries me is that "const product3 = ProductGroup(2)" does not compile while "const product4 = ProductGroup(8)" gives internal compiler error and "product5 = @[8].mapIt(ProductGroup(it))" compiles and gives "@[8 (invalid data!)]Pedal

© 2022 - 2024 — McMap. All rights reserved.