Function prototype: Difference between revisions

(added Ol)
Line 260:
 
=={{header|Common Lisp}}==
In Common Lisp, function prototypes can be used with <code>(declaim (inline func-name))</code> function arguments are taken when the function is defined. In addition, the argument types aren't needed.
{{incorrect|Common Lisp|None of this is related to function prototypes.}}
The [http://www.lispworks.com/documentation/HyperSpec/Body/03_da.htm ''lambda list''] is part of the function definition. It describes the arguments to a function.
 
<lang lisp>
<lang lisp>;; An empty lambda list () takes 0 parameters.
(declaim (inline no-args))
(defun 0args ()
(declaim (inline one-arg))
(format t "Called 0args~%"))
(declaim (inline two-args))
(declaim (inline optional-args))
 
(defun 0argsno-args ()
;; This lambda list (a b) takes 2 parameters.
(format nil "no arguments!"))
(defun 2args (a b)
(format t "Called 2args with ~A and ~A~%" a b))
 
(defun one-arg (x)
;; Local variables from lambda lists may have declarations.
; inserts the value of x into a string
;; This function takes 2 arguments, which must be integers.
(format nil "~a" x))
(defun 2ints (i j)
(declare (type integer i j))
(/ (+ i j) 2))</lang>
 
(defun 2argstwo-args (ax by)
When a program calls a function, Common Lisp uses the lambda list to check the number and type of arguments. Calls like <code>(0args "extra arg")</code>, <code>(2args)</code> and <code>(2ints 3.0 4/5)</code> would cause errors.
; same as function `one-arg', but with two arguments
(format nil "~a ~a" x y))
 
(defun optional-args (x &optional y) ; optional args are denoted with &optional beforehand
The lambda list has several more features.
; same as function `two-args', but if y is not given it just prints NIL
(format tnil "Called~a 0args~a~%" x y))
 
<lang lisp>;; Rest parameter, for variadic functions: r is a list of arguments.
(a b &rest r)
 
(no-args) ;=> "no arguments!"
;; Optional parameter: i defaults to 3, (f 1 2) is same as (f 1 2 3).
(a b &optional (i 3))
 
(one-arg 1) ;=> "1"
;; Keyword parameters: (f 1 2 :c 3 :d 4) is same as (f 1 2 :d 4 :c 3).
(a b &key c d)</lang>
 
(two-args 1 "example") ;=> "1 example"
* [[Variadic function#Common Lisp]] shows an example of <code>&rest</code>.
 
* [[Optional parameters#Common Lisp]] shows an example of <code>&key</code>.
(optional-args 1.0) ;=> "1.0 NIL"
 
(optional-args 1.0 "example") ;=> "1.0 example"
 
</lang>
 
=={{header|D}}==
Anonymous user