Introduction to functional programming and Emacs lisp Kun-Yuan Hsieh

Embed Size (px)

Text of Introduction to functional programming and Emacs lisp Kun-Yuan Hsieh

  • Introduction to functional programming and Emacs lispKun-Yuan Hsieh

  • Outline Tool: EmacsIntroduction to functional languageEmacs lisp

  • Emacs tutorial

  • Emacs?Unix editorAn integrated programming development environmentMaintain your programming styleEdit, compile, read and write email and new

  • Starting EmacsUnder 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 bindingsC for CtrlM for meta(ESC)Ex:C-xC-fM-x

  • Files Open a file: C-x C-fType a filename to open or create a fileSave a file: C-x C-sWite to a new file (save as): C-x C-w

  • CursorLeave the arrow alongC-f = forward to next characterC-b = back to previous characterC-n = move to next lineC-p = move to previous lineC-e = move to the end of the lineC-a = move to the start of the line

  • Scroll the screenScroll the display screen forward: C-vScroll the display screen backward: M-vGo to line M-x goto-line +numberTo the beginning: M-

  • Editing textC-j: newlineDelete:C-d:delete-char: delete-backward-charQuit Emacs:C-x C-c

  • Editing textC-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 replaceC-s: Incremental search forward (isearch-forward). C-r: Incremental search backward (isearch-backward).Search and replace:M-%SPACE,y: replacing currrent!: replace all match,n: do not replace current,q: quit

  • Splitting the windowsC-x 2: into two rowC-x 3: into two column

  • Change the working windowC-x o: to the next windowM -1 C-x o: to the previous windowC-x 0: close working window

  • Open a new frameA new frame: C-x 5 2Open a file in new frame:C-x 5 fClose a frame: C-x 5 0

  • ShellM-x shell

  • Functional programming

  • Introduction So far we have discussed imperative and O-O languagesImperative languages are design to meet the von Neumann archi.Functional programming is based on mathematical functions, and its non-imperativeFunctional programming is style of programming in which the primary method of computation is the application of functions to arguments

  • Brief historyAI in the mid-1950sLinguistics interest in natural language processingPsychologies interest in modeling human info. and the process of brainComputer must be able to process symbolic data and linked lists

  • Some languagesLanguage 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 concernScheme is a dialect of LISPWe will introduce Emacs Lisp

  • Mathematical functionMathematical function: a mapping of members of one set to another setDescribed by an expression or a tableThe evaluation order is controlled by recursion and conditional expressions

  • Functions Functions are defined by their names followed by parameters e.g. cube(x) = x*x*x domain set: real range set: real

  • Lambda expressionAlonzo Church, 1941A method for defining nameless functionA lambda expression is the function itself e.g. l (x)x*x*x evaluated for 2: (l(x)x*x*x)(2) => 8

  • l-expressionThe 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 parametersLISP took the idea of parameter abstractions from the l-calculus and combined it with notations that were particularly suitable for symbolic manipulation

  • Overview

    everything is a functionevery function has a typeFP consists of defining typesdefining functionsapplying functions and calculating the resulting expression

    f

    inputsoutput

  • Emacs lisp

  • Introduction GNU Emacs contains a complete Lisp system that allows the user to control the editorSome apps runs in the editor were written in Emacs LISP e.g.calendar (M-x calendar)

  • Running Emacs LISPOn UNIX system, execute emacsM-x ielm to enter iteractive mode *** Welcome to IELM *** Type (describe-mode) for help. ELISP> (+ 2 2) 4C-x C-e after the right hand parenthesis (+ 2 2) --1-:**-F1 ex1.el (Emacs-Lisp)--L11--Top------------------------- 4

  • First glance: expressionsLISP has simple syntaxRecall: everything is a functionELISP> (+ 1 2) 3 ELISP> (- 3 4) -1 ELISP> (length mormo") 5 ELISP> (concat cs" 2403") cs2403

  • Everything is a function(+ 2 2)Function nameArguments, supposed to be passed numbers

  • Arguments data typesType of data is passed to a function depends on what kind of information it uses e.g. + need numbers as arguments

  • Variable Number of Argumentsconcat, + or *, take any number of arguments. e.g. (+) => 0 (*) => 1 (+ 3) => 3 (* 3 4 5) => 60

  • ListLisp handle lists by putting them between parentheses, sometimes by a single quoteList is the central element of Lisp which represents program code and datae.g. '(rose violet daisy buttercup)

  • Number, lists inside a listList 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 atomsWhich 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 expressionsNested expression: (* (+ 1 2) (- 4 5)) => (1 + 2)*(4 - 5)Substring: ELISP> (substring (concat "abc" "def") 2 5) cdemessage: (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 functionThe not function inverts t or nil: e.g. ELISP> (not t) nil ELISP> (not nil) t ELISP> (not (string< "x" "y")) nil

  • Setting a variableSetq: 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 functionscar: yields the first item of the list e.g. ELISP> (car '(1 2 3 4)) 1cdr ("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: conscons: 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: lengthlength: 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...) "optional-documentation..." body...) e.g. (defun multiply-by-seven (number) "Multiply NUMBER by seven." (* 7 number))

  • Load functionsSave your source as xxx.elM-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- whileform: (while test-expr expr1 ... exprN) e.g. (while (< counter 10) body... (setq counter (+ counter) 1))

  • Recursion (defun triangle-using-cond (number) (cond (( 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

  • IOInput: 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.elName your function uID.el e.g. (defun u123456 (alist) SAMPLE FUNCTION (cdr alist))

  • Testing environment and flowUnder cs20., EmacsWe will load your function first by: e.g. M-x load-file ID.elThen 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/manual/emacs.htmlProgramming in Emacs LISP http://www.gnu.org/software/emacs/emacs-lisp-intro/emacs-lisp-intro.html