I’m fiddling around with enum and set. The attempt is to get a type checked expression of what I mean… The enum items come from fields in a CSV file.
I have an enum defined as below. I will have more questions, but my first question is how to write a set using my enum types as the basetype of the set.
Neither of the first BrokerBankLike statements will compile. (I can comment out each one) They give Error: ordinal type expected.
type
MyBrokerTypes {.pure.} = enum
valSvcFee = “Service Fee”,
valWirFnd = “Wire Funds”,
valSell = “Sell”,
valBuy = “Buy”,
valCasDiv = “Cash Dividend”
BrokerBankLike = set[enum]
BrokerBankLike = set[MyBrokerTypes]
# The line below does compile, but it isn't what I want.
BrokerBankLike = set[char]
Any suggestions on how I might do sets with enums ? Hi, just learning Nim as well, so I might be wrong but this is maybe what you want:
type
MyBrokerTypes {.pure.} = enum
valSvcFee ,
valWirFnd ,
valSell ,
valBuy ,
valCasDiv
var BrokerBankLike : set[MyBrokerTypes]
now every enum has an underlying int value (0,1,2, etc) , you can also assign your own but these values can only be ordinal: ints, chars or bools so strings like in your example won't work. You can use the $ operator to convert an enum value to a string.
Thanks for your reply. In my example, all the enum items also have an underlying int value as well as the text field. I am parsing csv files containing the text parts of the enums, so I need those text parts. To 'see', the $ operator shows the text field and the .ord operator shows the int part.
I have been trying several ideas. When I add another line to my test file, it miraculously compiles.
Remove the "BrokerBankLike = set[enum]" line and the "BrokerBankLike = set[char]" line and add
const
brokerBankLike: BrokerBankLike = {valSvcFee, valWirFnd}
And it all compiles. Looks like you want to convert a string into an enum, look here:https://stackoverflow.com/questions/42977509/nim-standard-way-to-convert-integer-string-to-enum
there is a parseEnum proc in strutils
Yes, I'm using parseEnum
proc findBrokerEnum(txt: string): MyBrokerTypes =
try:
result = parseEnum[MyBrokerTypes](txt)
except:
printf("MyBrokerType not found %s\n",txt)
quit(QuitFailure)