Introduction to functional programming and Emacs lisp Kun-Yuan Hsieh Outline Tool: Emacs Introduction to functional language Emacs lisp Emacs tutorial Emacs? Unix editor An integrated programming development environment Maintain your programming style Edit, compile, read and write email and new… Starting Emacs Under unix shell: > emacs filename (sometimes you need to use -nw) When using emacs, the files are actually being stored to RAM as a buffer. Any editing you do applies to the buffer, and then when you save, emacs writes the contents of the buffer to the disk. Screen layout keyboard bindings C for Ctrl M for meta(ESC) Ex: C-x C-f M-x Files Open a file: C-x C-f Type a filename to open or create a file Save a file: C-x C-s Wite to a new file (save as…): C-x C-w Cursor Leave the arrow along C-f = forward to next character C-b = back to previous character C-n = move to next line C-p = move to previous line C-e = move to the end of the line C-a = move to the start of the line Scroll the screen Scroll the display screen forward: C-v Scroll the display screen backward: M-v Go to line M-x goto-line +number To the beginning: M-< To the end: M-> Editing text C-j: newline Delete: C-d:delete-char <DEL>: delete-backward-char Quit Emacs: C-x C-c Editing text C-k: kill to the end of the line (kill-line). C-y:yank last killed text (yank). M-y: replace text just yanked with an earlier batch of killed text (yank-pop). Search and replace C-s: Incremental search forward (isearchforward). C-r: Incremental search backward (isearchbackward). Search and replace: M-% SPACE,y: replacing currrent !: replace all match <DEL>,n: do not replace current <ESC>,q: quit … Splitting the windows C-x 2: into two row C-x 3: into two column Change the working window C-x o: to the next window M -1 C-x o: to the previous window C-x 0: close working window Open a new frame A new frame: C-x 5 2 Open a file in new frame:C-x 5 f Close a frame: C-x 5 0 Shell M-x shell Functional programming Introduction So far we have discussed imperative and OO languages Imperative languages are design to meet the von Neumann archi. Functional programming is based on mathematical functions, and it’s nonimperative Functional programming is style of programming in which the primary method of computation is the application of functions to arguments Brief history AI in the mid-1950s Linguistics interest in natural language processing Psychologies interest in modeling human info. and the process of brain Computer must be able to process symbolic data and linked lists Some languages Language categories: imperative: Ada, C, Pascal, … object: Java, C++, Smalltalk … logic: Prolog, ... functional: Haskell, ML, Lisp, Scheme, … LISP(List Processing Language) is purely functional but added some imperative features for efficiency concern Scheme is a dialect of LISP We will introduce Emacs Lisp Mathematical function Mathematical function: a mapping of members of one set to another set Described by an expression or a table The evaluation order is controlled by recursion and conditional expressions I Domain set F O range set Functions Functions are defined by their names followed by parameters e.g. cube(x) = x*x*x domain set: real range set: real Lambda expression Alonzo Church, 1941 A method for defining nameless function A lambda expression is the function itself e.g. l (x)x*x*x evaluated for 2: (l(x)x*x*x)(2) => 8 l-expression The continuing influence of the l-calculus to (language design in) Functional Programming is in its typed varieties, i.e. all expressions in a typed l-calculus have a type, and so do formal parameters LISP took the idea of parameter abstractions from the l-calculus and combined it with notations that were particularly suitable for symbolic manipulation Overview inputs f output everything is a function every function has a type FP consists of defining types defining functions applying functions and calculating the resulting expression Emacs lisp Introduction GNU Emacs contains a complete Lisp system that allows the user to control the editor Some apps runs in the editor were written in Emacs LISP e.g.calendar (M-x calendar) Running Emacs LISP On UNIX system, execute emacs M-x ielm to enter iteractive mode *** Welcome to IELM *** Type (describe-mode) for help. ELISP> (+ 2 2) 4 C-x C-e after the right hand parenthesis (+ 2 2) --1-:**-F1 ex1.el 4 (Emacs-Lisp)--L11--Top------------------------- First glance: expressions LISP has simple syntax Recall: everything is a function ELISP> (+ 1 2) 3 ELISP> (- 3 4) -1 ELISP> (length ”mormo") 5 ELISP> (concat ”cs" ”2403") ”cs2403” … Everything is a function (+ 2 2) Arguments, supposed to be passed numbers Function name Arguments’ data types Type of data is passed to a function depends on what kind of information it uses e.g. + need numbers as arguments Variable Number of Arguments concat, + or *, take any number of arguments. e.g. (+) => 0 (*) => 1 (+ 3) => 3 (* 3 4 5) => 60 List Lisp handle lists by putting them between parentheses, sometimes by a single quote List is the central element of Lisp which represents program code and data e.g. '(rose violet daisy buttercup) Number, lists inside a list List can have number in it e.g. (+ 2 2) In Lisp, both data and programs are represented the same way which are both lists of words, numbers, or other lists, separated by whitespace and surrounded by parentheses. E.g.'(this list has (a list inside of it)) Atoms We call words atoms Which cannot be divided into any smaller parts e.g. numbers and single character symbols like +. Unlike an atom, a list can be split into parts. In a list, atoms are separated from each other by whitespace Some lisp expressions Nested expression: (* (+ 1 2) (- 4 5)) => (1 + 2)*(4 - 5) Substring: ELISP> (substring (concat "abc" "def") 2 5) ”cde” message: (message "This message appears in the echo area!") (message "There are %d %s in the office!” (- fill-column 14) "pink elephants") Comparison t if successful and nil if not: e.g. ELISP> (< 1 2) t ELISP> (< 1 0) nil ELISP> (= (+ 3 4) (- 10 2 1)) t ELISP> (string< "abc" "def") t ELISP> (string= "abc" "def") nil Comparison function The not function inverts t or nil: e.g. ELISP> (not t) nil ELISP> (not nil) t ELISP> (not (string< "x" "y")) nil Setting a variable Setq: setq carnivores '(lion tiger leopard)) Multiple setting (setq trees '(pine fir oak maple) herbivores '(gazelle antelope zebra)) Ex:(setting a counter) (setq counter 0) ;the initializer. (setq counter (+ counter 1));incrementer. counter; This is the counter. List functions car: yields the first item of the list e.g. ELISP> (car '(1 2 3 4)) 1 cdr ("could-er") produces the tail of a list e.g. ELISP> (cdr ‘(1 2 3 4) (2 3 4) ELISP> (car (cdr (cdr ‘(1 2 3 4)))) 3 List functions: cons cons: creates a list from a head and a tail e.g. ELISP> (cons 1 '(a b c)) (1 a b c) ELISP> (setq L (cons '(a b c) '(1 2 3))) ((a b c) 1 2 3) ELISP> (car L) (a b c) ELISP> (cdr L) (1 2 3) List functions: length length: find out # of elements in a list e.g. ELISP> (length '(buttercup)) 1 ELISP> (length '(daisy buttercup)) 2 ELISP> (length (cons 'violet '(daisy buttercup))) 3 Define functions (defun function-name (arguments...) "optionaldocumentation..." body...) e.g. (defun multiply-by-seven (number) "Multiply NUMBER by seven." (* 7 number)) Load functions Save your source as xxx.el M-x load-file Let let: special form to attach or bind a symbol to a value during a limited time e.g. (let ((birch 3) pine fir (oak 'some)) (message "Here are %d variables with %s, %s, and %s value." birch pine fir oak)) Control- while form: (while test-expr expr1 ... exprN) e.g. (while (< counter 10) body... (setq counter (+ counter) 1)) Recursion (defun triangle-using-cond (number) (cond ((<= number 0) 0) ((= number 1) 1) ((> number 1) (+ number (triangle-using-cond (1- number)))))) Project 5 quick sort Goal Define a function named uID to perform quick sort to sort a number list IO Input: a number list variety length e.g. ‘(1 4 5 8 9 6 3 5 4 ) ‘(100 589 32 1 5 844 58 5 2 12 6 8 ) Output: Message of sorting process(no specified form and conten ) e.g. “pick 1 as pilot” “pick 3 as pilot” … The sorted list e.g. (1 3 4 4 5 5 6 8 9) Print in the echo area, we will check your source code one by one Requirements Name your source ID.el e.g. 123456.el Name your function uID.el e.g. (defun u123456 (alist) “SAMPLE FUNCTION” (cdr alist)) Testing environment and flow Under cs20., Emacs We will load your function first by: e.g. M-x load-file ID.el Then feed some list to your function: e.g. (setq list1 ‘( 9 8 5 4 6 3 2 1)) (uID list1); evaluating your function Reference The Emacs editor http://www.gnu.org/software/emacs/manu al/emacs.html Programming in Emacs LISP http://www.gnu.org/software/emacs/emac s-lisp-intro/emacs-lisp-intro.html