Hi, I'm trying to translate a simple reactive programming exercise to nim and am getting stuck on the fact that I can't pass a seq[SubtypeOfFoo] to a proc expecting seq[Foo]. The only way around it seems to be quite ugly.
Here's what I'm trying to do.
Slightly simplified, this is how my code looks from the outside:
type
Cell* = ref object of RootObj
FValue: int
InputCell* = ref object of Cell
ComputeCell* = ref object of Cell
compute: ComputeFunc
ComputeFunc* = proc(vals: seq[int]): int
proc createInput*(value: int): InputCell
proc value*(c: Cell): int
proc `value=`*(c: InputCell, value: int)
proc createCompute*(inputs: seq[Cell], compute: ComputeFunc): ComputeCell
What I'd like to do is execute this test:
test "the value of a compute is determined by the value of the dependencies":
let
i1 = createInput(1)
c1 = createCompute(@[i1], proc(vals: seq[int]): int = vals[0] + 1)
check c1.value == 2
i1.value = 2
check c1.value == 3
But it doesn't work because I'm passing a seq[InputCell] where a seq[Cell] is required.
This works, but it's quite ugly and I kinda want a clean API:
test "the value of a compute is determined by the value of the dependencies":
let i1 = createInput(1)
var cells: seq[Cell] = newSeq[Cell](1)
cells[0] = i1
let c1 = createCompute(cells, proc(vals: seq[int]): int = vals[0] + 1)
check c1.value == 2
i1.value = 2
check c1.value == 3
Is there a better way to do this that doesn't require me to assign array elements one at a time?
Jehan: Array covariance is not typesafe
It is if the array isn't mutable.
jibal: It is if the array isn't mutable.
But Nim arrays are mutable. Array immutability is not really a very useful hypothetical.