1

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.

Nathan majicvr.com
  • 950
  • 2
  • 11
  • 31

2 Answers2

3

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

Alexis King
  • 43,109
  • 15
  • 131
  • 205
-1

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

Nathan majicvr.com
  • 950
  • 2
  • 11
  • 31
  • 3
    To a good first approximation if you are using `eval` you are making a mistake. –  Jul 12 '18 at 07:55
  • 1
    It's interesting to think how you would do this in python. I think it is `eval("np.zeros([{}, {}])".format(5, 5)`. I think that gets across how horrible `eval` is. –  Jul 12 '18 at 18:31