Sequence inheritance in Nimes

I have been experimenting with Nim for about a day now and I was wondering how you can inherit a type from the built-in ( seq in particular) so that procedures running on seq can also process a custom type.

I included a minimal example below in which TestCol wraps / proxies the sequence - will there be a way to have TestCol support map , filter , etc. without redefining procedures?

 type TestCol*[T] = object data*: seq[T] proc len*(b: TestCol): int = b.data.len proc `[]`*[T](b: TestCol[T], idx: int): T = b.data[idx] proc `[]=`*[T](b: var TestCol[T], idx: int, item: T) = b.data[idx] = item var x = newSeq[int](3) var y = TestCol[int](data: x) y[0] = 1 y[1] = 2 y[2] = 3 for n in map(y, proc (x: int): int = x + 1): echo($n) 

It is preferable that the solution does not require converting the user sequence to a regular sequence for performance reasons, while the conversions are less trivial than higher (although what I’ll do now, as suggested)

A use case in the real world is to implement array helpers on RingBuffer.nim

+6
source share
1 answer

Implicit converters could solve this problem:

 converter toSeq*[T](x: TestCol[T]): seq[T] = x.data 

Unfortunately, they are not called when calling proc waiting for openarray. I reported an error about this, but I'm not sure that it can be changed / fixed: https://github.com/nim-lang/Nim/issues/2652

+4
source

Source: https://habr.com/ru/post/986520/


All Articles