how to get a 'mixed bag seq' in Nim. I probably need to learn about generics...
In Crystal:
mixed_bag_seq = [1, "aa"]
here is Nim example that fails:
proc foo(a: int|string): int|string = # works: both string and int accepted
discard
type
mixed_seq = object
member1: seq[string] # works
# member2: seq[int|string] # Error: 'int or string' is not a concrete type
var bar: mixed_seq
Short answer, you can't. Seqs in Nim are single type only.
Long answer, object variants:
type
IntOrStringKind = enum Int, String
IntOrString = object
case kind: IntOrStringKind
of Int: intVal: int
of String: strVal: string
var x: seq[IntOrString]
x = @[IntOrString(kind: Int, intVal: 42), IntOrString(kind: String, strVal: "Hello world")]
echo x # @[(kind: Int, intVal: 42), (kind: String, strVal: "Hello world")]
I actually just released a library which automates the construction of these object variants specifically for cases like this. The solution using that is as simple as:
import sumtypes
type AcceptedTypes = int or string
sumTypeSeq(YourName, AcceptedTypes) # This emits a type of `YourName`(which is a seq with helpers) and a `YourNameEntry`(which is a object variant as pmunch demonstrated)
var a = @[1.YourNameEntry, "aa"]
case a[0]:
of int:
echo it, " Is int"
else: discard
case a[1]:
of string:
echo it
else: discard