Upgrade to Pro — share decks privately, control downloads, hide ads and more …

CSE240 Lecture 23

CSE240 Lecture 23

Introduction to Programming Languages
Functions in LISP
(202011)

B546a9b97d993392e4b22b74b99b91fe?s=128

Javier Gonzalez
PRO

January 23, 2017
Tweet

Transcript

  1. jgs CSE 240 Introduction to Programming Languages Lecture 23: Functions

    in LISP Javier Gonzalez-Sanchez javiergs@asu.edu PERALTA 230U Office Hours: By appointment
  2. Javier Gonzalez-Sanchez | CSE240 | Spring 2018 | 2 jgs

    Function Making § functions are created by calling a function-making macro. This macro is called defun. § the function returns the value of the last expression. (defun function-name-symbol (param1 param2 param3 ...) expr1 expr2 expr3 ... )
  3. Javier Gonzalez-Sanchez | CSE240 | Spring 2018 | 3 jgs

    Function Making § (defun do-hello-world ( ) "Hello, World!") DO-HELLO-WORLD § (do-hello-world) "Hello, World!" • (defun add-four (x) (+ x 4)) ADD-FOUR • (add-four 7) 11 • (defun hypotenuse (length width) (sqrt (+ (* length length)(* width width)))) HYPOTENUSE • (hypotenuse 7 9) 11.4017
  4. Javier Gonzalez-Sanchez | CSE240 | Spring 2018 | 4 jgs

    Function Making § (defun first-n-chars (string n reverse-iT) (if reverse-iT (subseq (reverse string) 0 n) (subseq string 0 n))) FIRST-N-CHARS § (first-n-chars "hello world" 5 nil) "hello" § (first-n-chars "hello world" 5 t) "dlrow" § (first-n-chars "hello world" 5 2013) "dlrow"
  5. jgs Exercises

  6. Javier Gonzalez-Sanchez | CSE240 | Spring 2018 | 6 jgs

    Test Yourselves 1 public static double factorial (double n) { double sum = 1; for (double i=0;i < n; i++) sum = sum * (1 + i); return sum; } public static void main(String [] args) { System.out.println(factorial(1000)+""); }
  7. Javier Gonzalez-Sanchez | CSE240 | Spring 2018 | 7 jgs

    Answer 1 (defun factorial (n) (let ((sum 1)) (dotimes (i n) (setf sum (* sum (1+ i))) ) sum ) ) FACTORIAL (factorial 1000) result? … double factorial (double n) { double sum = 1; for (double i=0;i < n; i++) sum = sum * (1 + i); return sum; } result?
  8. Javier Gonzalez-Sanchez | CSE240 | Spring 2018 | 8 jgs

    Test Yourselves 2 public static double factorial (double n) { if (n<=1) return 1; else return n * factorial (n-1); } public static void main(String [] args) { System.out.println(factorial(1000)+""); }
  9. Javier Gonzalez-Sanchez | CSE240 | Spring 2018 | 9 jgs

    Answer 2 (defun factorial (n) (if (<= n 0) 1 (* n (factorial (- n 1))) ) ) FACTORIAL (factorial 1000) result? … double factorial (double n) { if (n<=1) return 1; else return n * factorial (n-1); } result?
  10. jgs CSE 240 Introduction to Programming Languages Javier Gonzalez-Sanchez javiergs@asu.edu

    Spring 2020 Disclaimer. These slides can only be used as study material for the class CSE240 at ASU. They cannot be distributed or used for another purpose.