100 likes | 238 Views
How to define functions?. (DEFUN function-name parameter-list commands ) Example: (DEFUN myFunction (x y) (/ x y) ) To call this function, you would then type this (for example) : (myFunction 10 5) You do not have to declare the variable types!!. (DEFUN fact (x) (if (> x 0)
E N D
How to define functions? • (DEFUN function-name parameter-list commands ) • Example: (DEFUN myFunction (x y) (/ x y) ) • To call this function, you would then type this (for example) : (myFunction 10 5) • You do not have to declare the variable types!!
(DEFUN fact (x) (if (> x 0) (* x (fact (- x 1))) 1 ) ) The algorithm is as follows: if x > 0 then x * fact(x-1) else 1 A Factorial function This is an example of a recursive function!
Another function • Here is another function: (defun tryThis (x) (setq x (* x 4)) (setq x (+ x 3 4) (+ x -10) ); end of function • Note that a function with multiple statements in its body always return the value of its final statement.
Changing a list element The function below demonstrate how to change the second element of a list to another value. (DEFUN Change2nd ( list newvalue ) (cons (car list) (cons newvalue (cdr (cdr list)))) )
Optional arguments (1) You can specify that a particular argument (or arguments) are optional for a function as follows: (defun myFunc1 ( m &optional n ) (if n m 100) ) You can call this function with 1 or 2 arguments. If you supply 2 arguments, the function will return the value of m. If only 1 argument is supplied, the function returns 100.
Optional Arguments (2) This is another example (defun myFunc2 ( &optional (a 10) (b 20)) (* a b) ) This function has 2 optional arguments. Default values are specified for these arguments. If an optional argument is not included in the function call, the default values will be used.
Function with any number of arguments You can write a function that takes an unspecified number of arguments as follows: (defun anyfunction (x &rest y) y) (anyfunction 3) (anyfunction 3 4 5 6 7) In this function, if you specify more than 1 argument, the second argument onwards will be stored in the list named rest.
Eql • Eql(x y) Returns true only x and y if they are numbers of the same type with the same value, or if they are character objects that represent the same character. It is very similar to eq, except that it is more general. (eq ‘a ‘b) (eq ‘(a b) ‘(a b)) (eq ‘a ‘a) (eq 3 3.0) (eq #\a #\A) Eql is case and type sensitive.
Equal • Equal is more general than Eql. Try this: (equal ‘a ‘b) (equal ‘(a b) (‘a b)) (equal ‘a ‘a) (equal 3 3.0) (equal #\a #\A) • Now try the above expressions using Equalp. What are the differences??