Search code examples
pythonarraysnumpyhy

Using numpy.nditer in Hy


In python, the following code iterates a numpy array (the for loop), and the values of the numpy array are changed:

import numpy
a08_1 = numpy.arange(8).astype(numpy.uint8)
# a08_1: array([0, 1, 2, 3, 4, 5, 6, 7], dtype=uint8)
for x in numpy.nditer(a08_1, op_flags=['readwrite']):
  x[...] = 255 if x == 1 else 0
#
# a08_1: array([  0, 255,   0,   0,   0,   0,   0,   0], dtype=uint8)

Is it possible to do similarly in Hy? I can create the iterator with (numpy.nditer a08_1) but I do not know how to follow.

Thanks.


Solution

  • The equivalent Hy looks like this.

    (import numpy)
    (setv a08-1 (-> (numpy.arange 8) (.astype numpy.uint8)))
    (for [x (numpy.nditer a08-1 :op-flags ["readwrite"])]
      (assoc x Ellipsis (if (= x 1) 255 0)))