Skip to content

Commit 0348524

Browse files
authored
add user-supplied cmp() to find()
1 parent 9280821 commit 0348524

File tree

1 file changed

+11
-6
lines changed

1 file changed

+11
-6
lines changed

skiplists.nim

+11-6
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,9 @@ type
3333
value: T
3434
SkipList*[T] = ref SkipListObj[T]
3535

36+
SkipListCmp*[T] = proc(a, b: SkipList[T]): cmp {.noSideEffect.} ##
37+
## The procedure signature to use for comparing two SkipLists.
38+
3639
SkipListPred*[T] = proc(up: SkipList[T]; here: SkipList[T];
3740
child: SkipList[T]): bool ##
3841
## The predicate used to determine whether the SkipList
@@ -98,15 +101,16 @@ template `=!=`*(a, b: SkipList): bool =
98101
## `false` if SkipLists `a` and `b` share the same memory, else `true`.
99102
not(a === b)
100103

101-
template `<>`(a, b: SkipListObj): cmp =
104+
func `<>`[T](a, b: SkipListObj[T]): cmp =
105+
## Compare SkipListObj `a` and `b`.
102106
if a.value < b.value:
103107
Less
104108
elif a.value == b.value:
105109
Equal
106110
else:
107111
More
108112

109-
template `<>`(a, b: SkipList): cmp =
113+
func `<>`[T](a, b: SkipList[T]): cmp =
110114
## Compare SkipList `a` and `b`.
111115
if a.isNil or b.isNil:
112116
if a.isNil and b.isNil:
@@ -203,7 +207,7 @@ proc `$`(s: SkipList): string {.raises: [].} =
203207
result.add $s.down
204208

205209
when defined(release) or not skiplistsChecks:
206-
template check(s: SkipList; args: varargs[string, `$`]) = discard
210+
template check(s: SkipList; args: varargs[untyped]) = discard
207211
else:
208212
import std/strutils
209213

@@ -288,16 +292,17 @@ proc hash*(s: SkipList): Hash =
288292
h = h !& hash(item)
289293
result = !$h
290294

291-
proc find[T](s: SkipList[T]; value: SkipList[T]; r: var SkipList[T]): bool =
295+
proc find[T](s: SkipList[T]; value: SkipList[T]; r: var SkipList[T];
296+
compare: SkipListCmp[T] = `<>`): bool =
292297
## Find the SkipList `value` in SkipList `s`, storing the result in `r`;
293298
## returns `true` if the value was found, else `false`.
294299
if not s.isNil:
295300
r = s
296-
if value <> r == Equal:
301+
if compare(value, r) == Equal:
297302
result = true
298303
else:
299304
while true:
300-
case value <> r.over
305+
case compare(value, r.over)
301306
of Undefined:
302307
if r.down.isNil:
303308
break

0 commit comments

Comments
 (0)