Learning Elisp 01 Functions
Define a function
Specify the `&optional` or `&rest` argument in the arguments
1
2(defun multiply-many (x &optional y &rest operands)
3 "Multiplying the result of math expression on the arguments X, Y and OPERANDS"
4 (dolist (i operands)
5 (when i
6 (setq x (* x
7 (or y 1)
8 i))))
9 x)
10
11(multiply-many 2 3 8 19)
Function wihtout names
Lambda function - a function without a name
- pass a functionto another function
- don’t want to define for the function
1
2;;call an lambda function directly
3((lambda (x y)
4 (+ 100 x y))
5 10 20)
Invoking Function
Be aware that when invoking the function by passing symbol, `’` cannot be ignored, otherwise the gimmie-function will assume `named-version` is a variable instead of a function and tries to search for it in the variable space instead of the function space.
1
2;;calling the function by symbol
3(funcall '+ 2 2)
4
5;; define a function that acceptsa function
6
7(defun gimmie-function (fun x)
8 (message "Function: %s -- Result: %d"
9 fun
10 (funcall fun x)))
11
12;; store a lambda in a variable
13(setq function-in-variable (lambda (arg) (+ arg 1)))
14
15;; the equivalence of the above
16(defun named-version (arg)
17 (+ arg 1))
18
19;; Invoke lamda from parameter
20(gimmie-function (lambda (arg) (+ arg 1)) 5)
21
22;; Invoke lambda stored in variable (same as above)
23(gimmie-function function-in-variable 5)
24
25;; Invoke function by passing sybol
26(gimmie-function 'named-version 5)
If having a list of values that you want to pass to a function; use `apply` instead:
1(apply '+ '(2 2))
2
3(apply 'multiply-many '(1 2 3 4 5))
Interactive function (Command)
- They show up in M-x command list
- Can be used in key-bindings
- Can have parameters sent via prefix arguments `C-u`
1
2(defun my-first-command ()
3 (interactive)
4 (message "Hey it's worked"))
Interactive function allows you to pass argument to the function. The parameter says what type of arguments can be pass onto these interactive functions.
N - prompt for numbers or unmeric prefix argument p - Use numeric prefix without prompting (only prefix arguments) M - prompt for a string i - skip an “irrelevant” argument
Making the first example interactive:
1
2(defun multiply-many (x &optional y &rest operands)
3 "Multiplying the result of math expression on the arguments X, Y and OPERANDS"
4 (interactive "Nx:\nNy(optional):\nNAny more arguments:")
5 (dolist (i operands)
6 (when i
7 (setq x (* x
8 (or y 1)
9 i))))
10 (message "The result is %d" x))
Bind `multiply-many` to C-c z
1
2(global-set-key (kbd "C-c z") 'multiply-many)