How do I exit a PicoLisp function prematurely?

57 Views Asked by At

In Common Lisp we can exit a function prematurely with specified return value with "return-from". Is there a similar function in PicoLisp?

I've tried googling and ChatGPT to no avail. Interestingly, ChatGPT made up a non-existent "exit" function:

(de my-function (x)
  (if (= x 0)
    (exit "Early return value") ## Imagined by GPT
    (+ x 10) ) )

Something like this would be nice.

2

There are 2 best solutions below

0
hhy06 On

A partial answer to this is the quit function, which lets you quit a function prematurely.

Source: https://software-lab.de/doc/refQ.html#quit

(quit ['any ['any]]) Stops current execution. If no arguments are given, all pending finally expressions are executed and control is returned to the top level read-eval-print loop. Otherwise, an error handler is entered. The first argument can be some error message, and the second might be the reason for the error.

: (de foo (X) (quit "Sorry, my error" X))
-> foo
: (foo 123)                                  # 'X' is bound to '123'
123 -- Sorry, my error                       # Error entered
? X                                          # Inspect 'X'
-> 123
?                                            # Empty line: Exit
:

HOWEVER, note that quit function doesn't seem to produce a return value.

? (de foo (X) (quit "Sorry, my error" X))
-> foo
? (setq ret-value (foo "DOG"))
"DOG" -- Sorry, my error
? ret-value
-> NIL
0
ignis volens On

I think the answer is probably catch and throw:

(de foo (x)
  (catch 'done
   ...
   (throw 'done ...)
   ... not reached ...))

Certainly this is how you needed to do this in a lot of antique lisps.