0

I call a function, which outputs a list, I want to use afterwards. I try to bind the function's output to a variable, but instead of the list it gets assigned NIL.

My call and output (observe the newline in the output):

(nqthm-eval `(myghs 1 NIL ,g1)) ==> '(T (B . E) (D . D))

When I try to bind this output to a variable v it gets assigned NIL:

(setq v (nqthm-eval `(myghs 1 NIL ,g1))) ==> '(T (B . E) (D . D))
NIL

And an equality check afterwards indeed gives:

(equal v NIL) ==> T

It seems to me, that the function call to nqthm-eval is outputting the list and returning NIL, although I don't understand LISP enough for this yet.

My question: Is there a way to get the list part of the output/return of my function like (car (nqthm-eval ...)) or (get_output (nqthm-eval ...)) from the 'outside'?

Rainer Joswig
  • 136,269
  • 10
  • 221
  • 346
Alexander Boll
  • 228
  • 1
  • 7

1 Answers1

3

There is a difference between a function's return value and its output.

The return value is just the value (or values) of the last form and is captured by setq et al.

The output is sent to a stream and can only be captured from it.

E.g.,

(defun foo1 (x)
  (princ (1+ x))
  (1- x))
(foo1 12)

will print 13 and return 11.

If you want to capture both, you need

(defun foo2 (x)
  (values (1+ x) (1- x)))
(setf (values a b) (foo2 17))

and now a is 18 and b is 16.

PS. Actually, if you do not have control over the function source code and still want to capture its output, you can do it if you know where it sends its output. E.g.:

(setq b (with-output-to-string (*standard-output*)
          (setq a (foo1 1))))

now b is "2" (a string!) while a is 0 (a number!)

sds
  • 58,617
  • 29
  • 161
  • 278