How To Convert Slice To Sequence?
Asked Answered
W

2

6

I would like to specify a sequence directly from a slice (rather than iterating through the slice and adding each element individually to the sequence). I've tried a few different ways but the obvious ones don't seem to work.

var 
    x = newSeq(1..n)
    y: seq[int] = @[1..n]
    z: seq[int] = 1..n

The only thing I've managed to get to work is importing list comprehensions from future

var x: seq[int] = lc[x | (x <- 1..n), int]

I can't find any way in the docs that this can be done that doesn't involve importing the experimental stuff from future or overloading the sequence constructor myself.

Weismannism answered 16/4, 2015 at 19:5 Comment(0)
P
7

https://nim-lang.org/docs/sequtils.html#toSeq.t,untyped

import sequtils
var x = toSeq 1..n

For reference, you could also have written your own implementation to convert a slice to a seq:

proc toSeq2[T](s: Slice[T]): seq[T] =
  result = @[]
  for x in s.a .. s.b:
    result.add x
Proverb answered 16/4, 2015 at 19:26 Comment(0)
U
5

This will have good performance for large slices, since there will be no memory reallocations:

proc sliceToSeq[T](s: Slice[T]): seq[T] =
  result = newSeq[T](ord(s.b) - ord(s.a) + 1)
  var i = 0
  for x in s.a .. s.b:
    result[i] = x
    inc(i)
Umont answered 17/4, 2015 at 12:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.