[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Using '-1' in a method named '*'
From: |
Alejandro Sanchez |
Subject: |
Using '-1' in a method named '*' |
Date: |
Mon, 27 Feb 2017 11:06:00 +0100 |
Hello,
I have been trying to write a Guile library for 3D motion and I wrote a
‘vector3’ class and added the method ‘*’ for scaling a vector. This works fine
for any scalar, except for ‘-1’. Here is a minimal code example, I am using
Guile 2.0.14 on OS X 10.11.6:
(use-modules (oop goops))
(define-class <vector3> ()
;; Only one slot, for simlicity
(x #:init-value 0 #:getter get-x #:init-keyword #:x))
(define-method (* (n <real>) (v <vector3>))
;; Return anything, doesn't matter
3)
(define v (make <vector3> #:x 1))
(* -1 v) ; Does not work
(* -2 v) ; Works fine
The error message is:
<unnamed port>:14:0: In procedure #<procedure 104d7b8e0 at <current input>:14:0
()>:
<unnamed port>:14:0: In procedure -: Wrong type argument in position 1:
#<<vector3> 104ccdce0>
The backtrace is:
16:0 0 (#<procedure 104db6240 at <current input>:16:0 ()>)
This issue only happens when the argument is -1, it doesn’t happen for other
negative integers and it doesn’t happen for ‘-1.0’ either. And it’s not just
the literal ‘-1’, if instead I use an expression that evaluates to ‘-1’ like
‘(- 2 3)’ the same happens. However, changing the order of arguments in the
definition of the method does work.
The reason for this seems that the expression ‘(* -1 x)’ for any x is
re-written by Guile to ‘(- x)’, because by adding the following method it gets
working:
(define-method (- (v <vector3>))
2)
However, since '(* -1 v)’ gets re-written to ‘(- v)’ the result is ‘2' instead
of ‘3’. Granted, this is a contrived example and in any scenario I can think of
'(* -1 v)’ and ‘(- v)’ would yield the same result, but is this intended
behaviour? It was something that got me hung up over the last few days quite a
lot (I was already in the process of writing this email when it occurred to me
to define the ‘-‘ method).
- Using '-1' in a method named '*',
Alejandro Sanchez <=