I will get an undefined function warning about f2 in SBCL with following code sample. Is it possible that I can declare f2 first, like in C, to avoid the warning. I Googled, without any clue.
(defun f ()
(print (f2)))
(defun f2 ()
(print "f2"))
No! It is not possible. Python does not allow calling of a function before declaring it like C. This is possible in some languages like JavaScript but not in Python.
Use defun to define your own functions in LISP. Defun requires you to provide three things. The first is the name of the function, the second is a list of parameters for the function, and the third is the body of the function -- i.e. LISP instructions that tell the interpreter what to do when the function is called.
funcall applies function to args. If function is a symbol, it is coerced to a function as if by finding its functional value in the global environment.
In Lisp, a symbol such as mark-whole-buffer has code attached to it that tells the computer what to do when the function is called. This code is called the function definition and is created by evaluating a Lisp expression that starts with the symbol defun (which is an abbreviation for define function).
If you use the function before you define it in a single compilation unit, e.g., the same file, then the compiler will not complain about the undefined function (plain load
still may, so compile your code first!)
Otherwise, you can declaim
ftype
:
(declaim (ftype (function () t) f2)
meaning that f2
accepts no arguments and returns a single value of type t
.
However, it makes much more sense to compile the file where you use the function while the definition is already loaded. You can (and should!) use asdf as a Lisp-specific make(1): specifying dependencies so that the compiler has the definitions of all the functions while it compiles their users.
If the functions are in the same file, a compiler won't give a warning.
Example SBCL:
bash-3.2$ sbcl
This is SBCL 1.3.10, an implementation of ANSI Common Lisp.
More information about SBCL is available at <http://www.sbcl.org/>.
SBCL is free software, provided as is, with absolutely no warranty.
It is mostly in the public domain; some portions are provided under
BSD-style licenses. See the CREDITS and COPYING files in the
distribution for more information.
* (compile-file "/tmp/order.lisp")
; compiling file "/private/tmp/order.lisp" (written 28 NOV 2016 12:14:37 PM):
; compiling (DEFUN F ...)
; compiling (DEFUN F2 ...)
; /tmp/order.fasl written
; compilation finished in 0:00:00.178
#P"/private/tmp/order.fasl"
NIL
NIL
* (load *)
T
*
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With