Re: Idiomatic sequence functions

2020-02-14 Thread schmidh
Brilliant! Very kind of you. Thanks! 


Re: Idiomatic sequence functions

2020-02-14 Thread Hlaaftana
The idiomatic way to do this is to use an iterator. The 
[itertools](https://github.com/narimiran/itertools) library has this iterator 
under the name `islice`. Here is how the implementation for `take` would look 
anyway:


var lst = @[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

iterator take[T](s: openarray[T], n: int): T =
  assert n <= s.len
  var i = 0
  while i < n:
yield s[i]
inc i

for n in lst.take(5):
  echo n


Run


Re: Idiomatic sequence functions

2020-02-13 Thread schmidh
Awesome. Thanks for your answer! 


Re: Idiomatic sequence functions

2020-02-13 Thread treeform
Its [0 ..< 5]

You want slicing: 
[https://narimiran.github.io/nim-basics/#_indexing_and_slicing](https://narimiran.github.io/nim-basics/#_indexing_and_slicing)

See here: 
[https://play.nim-lang.org/#ix=2bFa](https://play.nim-lang.org/#ix=2bFa)


Idiomatic sequence functions

2020-02-13 Thread schmidh
Being new to Nim I'm missing basic list/sequence functions like e.g. take.


var lst = @[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for n in lst.take(5)
  echo n
# 1
# 2
# 3
# 4
# 5


Run

I would also assume that there would be an iterator but I couldn't find any in 
the documentation. Is there a reason for it? Like functional style in Nim is 
discouraged? Or is there another more Nim idiomatic way to do it? Slices might 
be used in this case but would throw an exception when the list is too short. 
Enlightening welcome! :-)