I'm trying to port Python's difflib's sequence matcher to nim. I want to be able to compare any two sequences of the same types, not just strings.
I have this type:
type
Diff[T] = object
a: seq[T]
b: seq[T]
b2j: Table[T, seq[int]]
How can I say that type T must support == and hash()?If I didn't mess up my concept syntax
type Diffable = concept x, y
`==`(x, y) is bool
hash(x) is Hash
See: https://nim-lang.org/docs/manual_experimental.html#concepts
And actual use cases:
type
Enqueueable = concept x, type T
x is ptr
x.next is Atomic[pointer]
type
IntrusiveStackable* = concept x, type T
x is ptr
x.next is T
type
StealableTask* = concept task, var mutTask, type T
## task is a ptr object and has a next/prev field
## for intrusive doubly-linked list based deque
task is ptr
task.prev is T
task.next is T
# A task has a parent field
task.parent is T
# task has a "fn" field with the proc to run
task.fn is proc (param: pointer) {.nimcall.}
type
TrainableLayer*[TT] = concept layer
block:
var trainable: false
for field in fields(layer):
trainable = trainable or (field is Variable[TT])
trainable
The last one is a bit hard, basically a concept must satisfy several properties, and that is checked by each statement returning true, so what I do there is creating a temporary bool called trainable in the concept and I check that recursively at least one field in the type or its subtypes is of Variable[TT] which would be something trainable in my framework. If there is at least one such field, it returns true and it's considered a TrainableLayer[TT].Checking with compiles should enough
when compiles(hash(a)): # a is the T object
doWith(a)
else:
{.error: "need hash implementation of " & T.type.}
It's checked during compile-time.