racket: equivalent to np.zeros((n, m))

205 Views Asked by At

I can't understand what I'm doing wrong here. Maybe a misplaced backquote.

The racket code:

(require math/array)
(define mask_cube
  (let ([leng 5])
    `(make-array #(,leng ,leng) 0)))

What I want it to do, written in python:

np.zeros((5,5))

Why isn't the comma working like I think it should? If there's a more elegant way to solve the problem, please let me know. Mostly I just want my pretty, short np.zeros() function

Moreover, if there's something fundamental I'm misunderstanding about backquote, commas, or racket (or even Lisp in general), please let me know.

2

There are 2 best solutions below

1
Alexis King On BEST ANSWER

You do not want eval here. Rather, you are quoting too much; the simple solution to your problem is to move the ` inwards to the appropriate place:

(define mask_cube
  (let ([leng 5])
    (make-array `#(,leng ,leng) 0)))

However, I’d generally avoid quotation if you’re a beginner; it is more complicated than it needs to be. Just use the vector function instead, which is easier to understand:

(define mask_cube
  (let ([leng 5])
    (make-array (vector leng leng) 0)))

For an in-depth treatment of quotation (with quasiquotation at the end), see What is the difference between quote and list?.

2
Nathan majicvr.com On

Wow, do I feel stupid. It's always the same thing: what's evaluated vs. what's just a list of symbols. The answer (see the eval):

(define mask_cube
  (let ([leng 5])
    (eval
      `(make-array #(,leng ,leng) 0))))

Still open to other answers that are coded with better style and am looking to modify this into a function/macro that translates np.zeros() and np.ones() into Lisp