Generic Sequences -


i have following snippet. second variable declaration not compile though:

type    coin = ref object   pen  = ref object  let    yes : seq[ref object] = @[coin(), coin(), coin()]  #compiles   no  : seq[ref object] = @[coin(), pen(), coin()]   #does not compile 

is possible in nim have generic seqs, java's list ?

nim sequences are generic, not putting same kind of objects in them. in java non-primitive types (including arrays) inherit either directly or indirectly object superclass , therefore having list<object> type can put in it. in nim not has have same root, , in case, while objects same, treated different types. need create class hierarchy java:

type   baseref = ref object of tobject   coinref = ref object of baseref   penref = ref object of baseref  let   test1: seq[baseref] = @[(baseref)coinref(), coinref(), coinref()]   test2: seq[baseref] = @[(baseref)coinref(), penref(), coinref()] 

note @[] list constructor still needs prodding in correct direction converting first element base type or inequality (a seq[baseref] not same seq[coinref], result type inference).

if need reason keep separate roots, being refs should ok cast them directly, can create helper procs:

type    anyref = ref object   coin = ref object   pen  = ref object  proc `^`(x: coin): anyref = cast[anyref](x) proc `^`(x: pen): anyref = cast[anyref](x)  let    yes : seq[anyref] = @[^coin(), ^coin(), ^coin()]   no  : seq[anyref] = @[^coin(), ^pen(), ^coin()] 

or maybe create converter procs don't require explicit conversion elements, first, inheritance version:

type    anyref = ref object   coin = ref object   pen  = ref object  converter toanyref(x: coin): anyref = cast[anyref](x) converter toanyref(x: pen): anyref = cast[anyref](x)  let    yes : seq[anyref] = @[coin().toanyref, coin(), coin()]   no  : seq[anyref] = @[coin().toanyref, pen(), coin()] 

Comments

Popular posts from this blog

java - Custom OutputStreamAppender not run: LOGBACK: No context given for <MYAPPENDER> -

java - UML - How would you draw a try catch in a sequence diagram? -

c++ - No viable overloaded operator for references a map -