timotheecour / Nim

Nim is a compiled, garbage-collected systems programming language with a design that focuses on efficiency, expressiveness, and elegance (in that order of priority).
http://nim-lang.org/
Other
2 stars 0 forks source link

add overload `toSeq(iterable, n)` or add `toSeqN(iterable, n)` to get first N results #737

Open timotheecour opened 3 years ago

timotheecour commented 3 years ago

add template toSeqN[T](iterable[T], n: int): seq[T] and maybe deprecate: proc readLines*(filename: string, n: Natural): seq[string] or at least indicate it can be done via toSeqN

benefits

links

see also related proposal take https://github.com/timotheecour/Nim/issues/504

iterator take[T](a: iterable[T], n: int): T =
  ## iterates over first `n` elements of `a`

but it doesn't really make toSeqN obsolete because knowing n allows the pre-allocation

juancarlospaco commented 3 years ago

window: Slice[int] ?.

timotheecour commented 3 years ago

that's reasonable but i think the main reason for toSeqN is that it allows pre-allocating. you could make things more composable as follows:

let s = myiter().sliceIter(10..<20).toSeqN(10)

where sliceIter is lazy eg:

iterator sliceIter[T](a: iterable[T], window: Slice[int]): T =
  for i in 0..<window.a:
    discard a()
  for i in 0..<window.len:
    yield b()

what would be even better would be if there's a way to have iterators with known length be able to forward this information to callers (in D it's easy with ranges that can have arbitrary properties via duck typing)

juancarlospaco commented 3 years ago

I tried to send PR in the past adding start: Natural; ends: Positive but they rejected, at that time I think Slice[int] was not ready.

strutils can also be improved a lot with start/end arguments, because basically is all for loops over char ops.

timotheecour commented 3 years ago

tried to send PR in the past

which one(s)?

adding start: Natural; ends: Positive

that's not good, it prevents special case of empty window; Slice[int] is the better API (self documenting on call site with foo(3..5) etc)

strutils can also be improved a lot

many ways it can be improved indeed:

but maybe the right way is to gradually add APIs to std/strbasics which is newer / meant for performance and using better patterns

juancarlospaco commented 3 years ago

I know Slice[int] is better than start: Natural; ends: Positive.

The iterator with windows is nice.

I think is interesting if strutils moves to openArray[char], it should be possible to create a {array[char]: T} container.

timotheecour commented 3 years ago

a {array[char]: T} container.

what do you mean?

juancarlospaco commented 3 years ago

Just an idea of an {array[char]: Option[T]} container, where lhs is static alloc.