[nim-dev] Shift operation for array elements

  • From: Stefan_Salewski <mail@xxxxxxxxxxxx>
  • To: nim-dev@xxxxxxxxxxxxx
  • Date: Fri, 23 Sep 2016 18:24:58 +0000

Do we have a shift operation for array elements in Nim like this one? Well, now 
we have.

The filling with default value: I am using a compiler initialized var to get 
the default. Is that the suggested way?

```nim 
proc shift[T](a: var openarray[T]; d: int) =
  ## Shift a right by d places for positive d or
  ## left for negative d.
  ## Shifted in elements are filled with default value.
  var
    h: T
    j: int
  if d > 0: # right shift
    j = a.high
    while j >= d:
      a[j] = a[j - d]
      dec(j)
    j = min(d, a.len)
    for i in 0 ..< j:
      a[i] = h
  elif d < 0: # left shift
    j = -d
    while j < a.len:
      a[j + d] = a[j]
      inc(j)
    j = max(a.len + d, 0)
    for i in j .. a.high:
      a[i] = h

var ta = [1,1,1]
shift(ta, 1)
assert(ta == [0,1,1])

ta = [1,1,1]
shift(ta, 2)
assert(ta == [0,0,1])

ta = [1,1,1]
shift(ta, 3)
assert(ta == [0,0,0])

ta = [1,1,1]
shift(ta, 4)
assert(ta == [0,0,0])

ta = [1,1,1]
shift(ta, -1)
assert(ta == [1,1,0])

ta = [1,1,1]
shift(ta, -2)
assert(ta == [1,0,0])

ta = [1,1,1]
shift(ta, -3)
assert(ta == [0,0,0])

ta = [1,1,1]
shift(ta, -4)
assert(ta == [0,0,0])
``` 

Other related posts: