difference result by eval in macro and in S-expr

Started by lyl, April 27, 2019, 04:07:33 PM

Previous topic - Next topic

lyl

I think the following two examples say the same thing, but they give different results, why?



Example No. 1:
(define-macro (m lst)
  (eval lst))
(m '(+ 4 5)) ;; -> (+ 4 5)


Example No. 2:
(eval '(+ 4 5)) ;; -> 9

rrq

#1
mmm, did you check http://www.newlisp.org/downloads/newlisp_manual.html#define-macro">//http://www.newlisp.org/downloads/newlisp_manual.html#define-macro ?



The key point is that for m, its parameter lst gets bound to the un-evaluated argument '(+ 4 5), whereas in example 2 the eval function's parameter gets the evaluated argument (+ 4 5), i.e, without the single-quote. In other words, (m '(+ 4 5)) is actually the same as (eval ''(+ 4 5))
If you'd want an "m" function to be the same as an "eval" function, you'd use "define" rather than "define-macro". (Not totally the same, since "m" binds "lst" before calling "eval", but that's a separate concern)



hth

lyl

#2
Then, in the following example
(define(f lst)
  (+ lst 1))

(setq a '(+ 2 3))
(f a)


As arguments of function in lisp are evaled first, I think (f a) is the same as (+ (+ 2 3) 1) which should be 6, but what I get is: "ERR: value expected in function + : (+ 2 3)". Why?

cameyo

#3
Maybe you can use letex:
(define(f lst)
  (letex (x lst) (+ x 1)))

(setq a '(+ 2 3))
;-> (+ 2 3)

(f a)
;-> 6


Try this:
(define types '("nil" "true" "int" "float" "string" "symbol" "context"
    "primitive" "import" "ffi" "quote" "expression" "lambda" "fexpr" "array"
    "dyn_symbol"))

(define (typeof v)
    (types (& 0xf ((dump v) 1))))

(define(f lst)
  (letex (x lst)
    (println (list? lst))
    (println (symbol? lst))
    (println (list? x))
    (println (symbol? x))
    (println (dump lst))
    (println (dump x))
    (println (typeof lst))
    (println (typeof x))
  (+ x 1)))

(setq a '(+ 2 3))
;-> (+ 2 3)

(f a)
;-> true
;-> nil
;-> nil
;-> nil
;-> (7026864 59 7012912 7030672 7026896)
;-> (7030096 386 7012912 7012912 5)
;-> expression
;-> int
;-> 6

lyl

#4
Thank you, cameyo.  I think the argument "lst" of "f" has been evaled during the call of (f a), so why must  it be evaled again by "letex" in function body ?

And could you please give more information about the function "typeof"?

cameyo

#5
Hi lyl,

i'm not an expert, but i think "evaluated" is different from "expanded". Maybe a guru will highligth this question.

The typeof function show the type of the argument; the core function is dump (see the manual for information).

ciao