One can exploit subranges to create a new type that is a subset of char, like so:
type
CapitalLetters = range['A'..'Z']
var s = "The capital letters are: "
for i in low(CapitalLetters)..high(CapitalLetters):
s &= $i
echo s
But is it possible to derive a type for a non-contiguous subset. Ideally something like this (non-working of course):
type
WASDLetters = set{'W','A','S','D'}
It's not possible. Workaround:
type
WASDLetters = distinct char
const
W = WASDLetters('W')
A = WASDLetters('A')
S = WASDLetters('S')
D = WASDLetters('D')
Thanks for the suggestion. But this doesn't get any compile time type checking to make sure chars used are in the desired set, does it?
# raises type error
var a: CapitalLetters = 'q'
# doesn't raise type error
var b: WASDLetters = 'q'
Obviously there are other ways I can handle this -- such as something along the lines of what Haskeller's call a "smart constructor" -- but I was hoping to see how far I could push Nim's type system (which I quite enjoy!).
since b is declared as WASDLetters , it's inferred so.
But since it's WASDLetters you won't be able to ord(b) and it's detected during compile-time checking.