Skip to content

Commit

Permalink
add enumerate; solve warning about Iterable T
Browse files Browse the repository at this point in the history
  • Loading branch information
litlighilit committed Apr 9, 2024
1 parent 630b9fd commit 35b040a
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 16 deletions.
27 changes: 19 additions & 8 deletions src/pylib.nim
Original file line number Diff line number Diff line change
Expand Up @@ -218,21 +218,32 @@ iterator items*[T](f: Filter[T]): T =
for x in f.iter():
yield x

iterator enumerate*[T](x: Iterable[T]): (int, T) =
var i = 0
for v in x:
yield (i, v)
i.inc

when defined(js):
proc list*[T](iter: Iterable[T]): seq[T]{.error:"""
# XXX: a workaround, at least support some types

This comment has been minimized.

Copy link
@ringabout

ringabout Apr 9, 2024

It works on the devel branch; probably fixed by nim-lang/Nim#23470

This comment has been minimized.

Copy link
@litlighilit

litlighilit Apr 9, 2024

Author Member

Ops! Sounds great.

Can't wait to have a try.

This has been bothering me for a long time.

func list*[T](arr: openArray[T]): seq[T] =
for i in arr:
result.add i
proc list*[T](iter: not openArray[T] and Iterable[T]): seq[T]{.error:"""
XXX: when for js:
nim compiler will complain about `for i in iter`'s `i` ,
saying: internal error: expr(nkBracketExpr, tyUserTypeClassInst)
""".} # TODO: when solved, remove workaround below.
else:
# it has side effects as it calls `items`
proc list*[T](iter: Iterable[T]): seq[T] =
for i in iter:
result.add i
# XXX: a workaround, at least support some types
func list*[T](arr: openArray[T]): seq[T] =
for i in arr:
result.add i
when compiles(iter.len):
result = newSeq[T](iter.len)
for i, v in enumerate(iter):
result[i] = v
else:
for i in iter:
result.add i

when defined(js):
func filter*[T](comp: NoneType | proc(arg: T): bool, iter: Iterable[T]): Filter[T]{.error: """
Expand Down Expand Up @@ -263,7 +274,7 @@ else:
let filtered = list(filter(None, values))
doAssert filtered == @["yes", "no", "why"]

result = filter[T](pylib.bool, iter)
result = filter[T](toBool, iter)


proc input*(prompt = ""): string =
Expand Down
8 changes: 0 additions & 8 deletions src/pylib/range.nim
Original file line number Diff line number Diff line change
Expand Up @@ -65,11 +65,3 @@ func min*[T](x: Range[T]): T {.inline.} =
func max*[T](x: Range[T]): T {.inline.} =
## Get maximum value from range
x[if x.step > 0: x.len - 1 else: 0]

func list*[T](x: Range[T]): seq[T] =
## Generate sequence of numbers from given range
result = newSeq[T](x.len)
var i = 0
for val in x:
result[i] = val
inc i

0 comments on commit 35b040a

Please sign in to comment.