Skip to content

Commit

Permalink
fix(py): min/max: support arg of Comparable
Browse files Browse the repository at this point in the history
  • Loading branch information
litlighilit committed Feb 2, 2025
1 parent 676f407 commit 233eeab
Showing 1 changed file with 15 additions and 2 deletions.
17 changes: 15 additions & 2 deletions src/pylib/builtins/min_max.nim
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,10 @@ template addKeyIfExist(result; kw) =
result.add nnkExprEqExpr.newTree(keyId, kw[keyId])

type
PyLibKey*[T, R] = proc (x: T): R
Comparable* = concept a, b
## internal.
a < b is bool
PyLibKey*[T; R: Comparable] = proc (x: T): R

template withDefaultImpl(resultExpr){.dirty.} =
result = default
Expand All @@ -53,8 +56,11 @@ template cmpByKey[T](dir, key; a, b: T): T =
if dir(key(a), key(b)): a
else: b

template asis[T](x: T): T = x

template gen(sym, dir, symName){.dirty.} =
## min/max(a, b) is alreadly defined by `system`
## min/max(a, b) for builtin types is alreadly defined by `system`
func sym*[T: Comparable](a, b: T): T = cmpByKey(dir, asis, a, b)
func sym*[T; R](a, b: T; key: PyLibKey[T, R]): T = cmpByKey(dir, key, a, b)
func sym*[T](a, b: T; key: NoneType): T = sym(a, b)

Expand All @@ -79,6 +85,13 @@ template gen(sym, dir, symName){.dirty.} =
withDefaultImpl cmpByKey(dir, key, result, i)

macro sym*(kwargs: varargs[untyped]): untyped =
## for argument list: `(*args, key)`
##
## raises *compile-time* `TypeError` when Python does so, in cases:
##
## - `()` # no arg
## - `(arg[, default][, key])` # only one arg
## - `(*args, default[, key])` # both args and default are given
let nka = kwargs.len

var
Expand Down

0 comments on commit 233eeab

Please sign in to comment.