Search code examples
pythonnumpylispracketbackquote

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


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.


Solution

  • 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?.