INF4820: Algorithms for Artificial Intelligence and Natural Language Processing. More Common Lisp

Similar documents
INF4820: Algorithms for Artificial Intelligence and Natural Language Processing. Common Lisp Fundamentals

A little bit of Lisp

INF4820. Common Lisp: Closures and Macros

Symbolic Programming. Dr. Zoran Duric () Symbolic Programming 1/ 89 August 28, / 89

CS 480. Lisp J. Kosecka George Mason University. Lisp Slides

Common LISP Tutorial 1 (Basic)

Functional programming with Common Lisp

LISP. Everything in a computer is a string of binary digits, ones and zeros, which everyone calls bits.

LISP - SEQUENCES. The function make-sequence allows you to create a sequence of any type. The syntax for this function is:

Gene Kim 9/9/2016 CSC 2/444 Lisp Tutorial

Artificial Intelligence Programming

Department of Computer and information Science Norwegian University of Science and Technology

Lecture #2 Kenneth W. Flynn RPI CS

Common LISP-Introduction

Common Lisp. Blake McBride

Modern Programming Languages. Lecture LISP Programming Language An Introduction

Lecture Notes on Lisp A Brief Introduction

Imperative, OO and Functional Languages A C program is

CSCI337 Organisation of Programming Languages LISP

Symbolic Computation and Common Lisp

Introduction to Lisp

FUNKCIONÁLNÍ A LOGICKÉ PROGRAMOVÁNÍ 4. LISP: PROMĚNNÉ, DALŠÍ VLASTNOSTI FUNKCÍ, BLOKY, MAPOVACÍ FUNKCIONÁLY, ITERAČNÍ CYKLY,

Announcement. Overview. LISP: A Quick Overview. Outline of Writing and Running Lisp.

Algorithms for AI and NLP (INF4820 Lisp & FSAs)

Robot Programming with Lisp

FUNKCIONÁLNÍ A LOGICKÉ PROGRAMOVÁNÍ 2. ÚVOD DO LISPU: ATOMY, SEZNAMY, FUNKCE,

Functions, Conditionals & Predicates

11/6/17. Functional programming. FP Foundations, Scheme (2) LISP Data Types. LISP Data Types. LISP Data Types. Scheme. LISP: John McCarthy 1958 MIT

(defvar *state* nil "The current state: a list of conditions.")

Functional Programming. Pure Functional Programming

Allegro CL Certification Program

Recursion & Iteration

Lisp. Versions of LISP

Notes on Higher Order Programming in Scheme. by Alexander Stepanov

Lisp Basic Example Test Questions

CIS4/681 { Articial Intelligence 2 > (insert-sort '( )) ( ) 2 More Complicated Recursion So far everything we have dened requires

Documentation for LISP in BASIC

Functional Programming. Big Picture. Design of Programming Languages

Principles of Programming Languages Topic: Functional Programming Professor L. Thorne McCarty Spring 2003

Functional Programming. Pure Functional Languages

Functional Languages. CSE 307 Principles of Programming Languages Stony Brook University

Type-checking on Heterogeneous Sequences

Robot Programming with Lisp

Lambda Calculus and Lambda notation in Lisp II. Based on Prof. Gotshalks notes on Lambda Calculus and Chapter 9 in Wilensky.

Debugging in LISP. trace causes a trace to be printed for a function when it is called

Summer 2017 Discussion 10: July 25, Introduction. 2 Primitives and Define

19 Machine Learning in Lisp

CSCE476/876 Fall Homework 3: Programming Assignment Using Emacs and Common Lisp. 1 Exercises (15 Points) 2. 2 Find (6 points) 4

Streams and Lazy Evaluation in Lisp

A LISP Interpreter in ML

User-defined Functions. Conditional Expressions in Scheme

Racket. CSE341: Programming Languages Lecture 14 Introduction to Racket. Getting started. Racket vs. Scheme. Example.

A Genetic Algorithm Implementation

Introductory Scheme. Revision 1

Organization of Programming Languages CS3200/5200N. Lecture 11

Allegro CL Certification Program

Fall 2018 Discussion 8: October 24, 2018 Solutions. 1 Introduction. 2 Primitives

XLISP PLUS. Reference Manual. Version 3.0

Scheme Tutorial. Introduction. The Structure of Scheme Programs. Syntax

Functional Programming. Pure Functional Languages

Announcements. Today s Menu

FP Foundations, Scheme

A Brief Introduction to Scheme (II)

University of Massachusetts Lowell

Look at the outermost list first, evaluate each of its arguments, and use the results as arguments to the outermost operator.

CSC 533: Programming Languages. Spring 2015

Functional Programming

CS 61A Interpreters, Tail Calls, Macros, Streams, Iterators. Spring 2019 Guerrilla Section 5: April 20, Interpreters.

Scheme. Functional Programming. Lambda Calculus. CSC 4101: Programming Languages 1. Textbook, Sections , 13.7

Building a system for symbolic differentiation

Lisp: Question 1. Dr. Zoran Duric () Midterm Review 1 1/ 13 September 23, / 13

NST: A Unit Test Framework for Common Lisp

;; definition of function, fun, that adds 7 to the input (define fun (lambda (x) (+ x 7)))

Functional programming techniques

Chapter 1. Fundamentals of Higher Order Programming

CMSC 331 Final Exam Fall 2013

Object Oriented Programming (OOP)

Jatha. Common Lisp in Java. Ola Bini JRuby Core Developer ThoughtWorks Studios.

SCHEME 8. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. March 23, 2017

1 CLWEB INTRODUCTION 1

CS 342 Lecture 7 Syntax Abstraction By: Hridesh Rajan

Intro. Scheme Basics. scm> 5 5. scm>

CSCC24 Functional Programming Scheme Part 2

Fall 2017 Discussion 7: October 25, 2017 Solutions. 1 Introduction. 2 Primitives

COP4020 Programming Languages. Functional Programming Prof. Robert van Engelen

Lecture #5 Kenneth W. Flynn RPI CS

CS 842 Ben Cassell University of Waterloo

SCHEME 7. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. October 29, 2015

Lisp as a Second Language Chapter 1 Functional Style

Introduction to ACL2. CS 680 Formal Methods for Computer Verification. Jeremy Johnson Drexel University

University of Maine School of Computing and Information Science COS 470/570

FUNKCIONÁLNÍ A LOGICKÉ PROGRAMOVÁNÍ 3. LISP: ZÁKLADNÍ FUNKCE, POUŽÍVÁNÍ REKURZE,

Project 2: Scheme Interpreter

UMBC CMSC 331 Final Exam

CSCE 314 TAMU Fall CSCE 314: Programming Languages Dr. Flemming Andersen. Haskell Functions

Introduction to Scheme

Functional Languages. Hwansoo Han

LECTURE 16. Functional Programming

Chapter 15. Functional Programming Languages

Functional Programming Languages (FPL)

Transcription:

INF4820: Algorithms for Artificial Intelligence and Natural Language Processing More Common Lisp Stephan Oepen & Murhaf Fares Language Technology Group (LTG) September 6, 2017

Agenda 2 Previously Common Lisp essentials S-expressions (= atoms or lists of s-expressions) Recursion Quote List processing Identity vs. Equality

Agenda 2 Previously Common Lisp essentials S-expressions (= atoms or lists of s-expressions) Recursion Quote List processing Identity vs. Equality Today More Common Lisp Higher-order functions Argument lists Iteration: (the mighty) loop Additional data structures

Conditional Evaluation 3 Examples? (defparameter foo 42)? (if (numberp foo) "number" "something else")

Conditional Evaluation 3 Examples? (defparameter foo 42)? (if (numberp foo) "number" "something else") "number"

Conditional Evaluation 3 Examples? (defparameter foo 42)? (if (numberp foo) "number" "something else") "number"? (cond ((< foo 3) "less") ((> foo 3) "more") (t "equal"))

Conditional Evaluation 3 Examples? (defparameter foo 42)? (if (numberp foo) "number" "something else") "number"? (cond ((< foo 3) "less") ((> foo 3) "more") (t "equal")) "more"

Conditional Evaluation 3 Examples? (defparameter foo 42)? (if (numberp foo) "number" "something else") "number"? (cond ((< foo 3) "less") ((> foo 3) "more") (t "equal")) "more" General Form (if predicate then clause else clause ) (cond ( predicate 1 clause 1 + ) ( predicate 2 clause 2 + ) ( predicate i clause i + ) (t default clause + ))

Rewind: A Note on Symbol Semantics 4 Symbols can have values as functions and variables at the same time. # (sharp-quote) gives us the function object bound to a symbol.? (defun foo (x) (* x 1000))

Rewind: A Note on Symbol Semantics 4 Symbols can have values as functions and variables at the same time. # (sharp-quote) gives us the function object bound to a symbol.? (defun foo (x) (* x 1000))? (defparameter foo 42) 42

Rewind: A Note on Symbol Semantics 4 Symbols can have values as functions and variables at the same time. # (sharp-quote) gives us the function object bound to a symbol.? (defun foo (x) (* x 1000))? (defparameter foo 42) 42? (foo foo)

Rewind: A Note on Symbol Semantics 4 Symbols can have values as functions and variables at the same time. # (sharp-quote) gives us the function object bound to a symbol.? (defun foo (x) (* x 1000))? (defparameter foo 42) 42? (foo foo) 42000

Rewind: A Note on Symbol Semantics 4 Symbols can have values as functions and variables at the same time. # (sharp-quote) gives us the function object bound to a symbol.? (defun foo (x) (* x 1000))? (defparameter foo 42) 42? (foo foo) 42000? foo 42

Rewind: A Note on Symbol Semantics 4 Symbols can have values as functions and variables at the same time. # (sharp-quote) gives us the function object bound to a symbol.? (defun foo (x) (* x 1000))? (defparameter foo 42) 42? (foo foo) 42000? foo 42? # foo #<Interpreted Function FOO>

Rewind: A Note on Symbol Semantics 4 Symbols can have values as functions and variables at the same time. # (sharp-quote) gives us the function object bound to a symbol.? (defun foo (x) (* x 1000))? (defparameter foo 42) 42? (foo foo) 42000? foo 42? # foo #<Interpreted Function FOO>? (funcall # foo foo) 42000

Rewind: A Note on Symbol Semantics 4 Symbols can have values as functions and variables at the same time. # (sharp-quote) gives us the function object bound to a symbol.? (defun foo (x) (* x 1000))? (defparameter foo 42) 42? (foo foo) 42000? foo 42? # foo #<Interpreted Function FOO>? (funcall # foo foo) 42000 # and funcall (as well as apply) are useful when passing around functions as arguments.

Higher-Order Functions 5 Functions that accept functions as arguments or return values. Functions in Lisp are first-class objects. Can be created at run-time, passed as arguments, returned as values, stored in variables... just like any other type of data.

Higher-Order Functions 5 Functions that accept functions as arguments or return values. Functions in Lisp are first-class objects. Can be created at run-time, passed as arguments, returned as values, stored in variables... just like any other type of data.? (defun filter (list test) (cond ((null list) nil) ((funcall test (first list)) (cons (first list) (filter (rest list) test))) (t (filter (rest list) test))))

Higher-Order Functions 5 Functions that accept functions as arguments or return values. Functions in Lisp are first-class objects. Can be created at run-time, passed as arguments, returned as values, stored in variables... just like any other type of data.? (defun filter (list test) (cond ((null list) nil) ((funcall test (first list)) (cons (first list) (filter (rest list) test))) (t (filter (rest list) test))))

Higher-Order Functions 5 Functions that accept functions as arguments or return values. Functions in Lisp are first-class objects. Can be created at run-time, passed as arguments, returned as values, stored in variables... just like any other type of data.? (defun filter (list test) (cond ((null list) nil) ((funcall test (first list)) (cons (first list) (filter (rest list) test))) (t (filter (rest list) test))))? (defparameter foo (11 22 33 44 55))

Higher-Order Functions 5 Functions that accept functions as arguments or return values. Functions in Lisp are first-class objects. Can be created at run-time, passed as arguments, returned as values, stored in variables... just like any other type of data.? (defun filter (list test) (cond ((null list) nil) ((funcall test (first list)) (cons (first list) (filter (rest list) test))) (t (filter (rest list) test))))? (defparameter foo (11 22 33 44 55))? (filter foo # evenp)

Higher-Order Functions 5 Functions that accept functions as arguments or return values. Functions in Lisp are first-class objects. Can be created at run-time, passed as arguments, returned as values, stored in variables... just like any other type of data.? (defun filter (list test) (cond ((null list) nil) ((funcall test (first list)) (cons (first list) (filter (rest list) test))) (t (filter (rest list) test))))? (defparameter foo (11 22 33 44 55))? (filter foo # evenp) (22 44)

Higher-Order Functions 5 Functions that accept functions as arguments or return values. Functions in Lisp are first-class objects. Can be created at run-time, passed as arguments, returned as values, stored in variables... just like any other type of data.? (defun filter (list test) (cond ((null list) nil) ((funcall test (first list)) (cons (first list) (filter (rest list) test))) (t (filter (rest list) test))))? (defparameter foo (11 22 33 44 55))? (filter foo # evenp) (22 44) Functions

Higher-Order Functions 5 Functions that accept functions as arguments or return values. Functions in Lisp are first-class objects. Can be created at run-time, passed as arguments, returned as values, stored in variables... just like any other type of data.? (defun filter (list test) (cond ((null list) nil) ((funcall test (first list)) (cons (first list) (filter (rest list) test))) (t (filter (rest list) test))))? (defparameter foo (11 22 33 44 55))? (filter foo # evenp) (22 44) Functions, recursion

Higher-Order Functions 5 Functions that accept functions as arguments or return values. Functions in Lisp are first-class objects. Can be created at run-time, passed as arguments, returned as values, stored in variables... just like any other type of data.? (defun filter (list test) (cond ((null list) nil) ((funcall test (first list)) (cons (first list) (filter (rest list) test))) (t (filter (rest list) test))))? (defparameter foo (11 22 33 44 55))? (filter foo # evenp) (22 44) Functions, recursion, conditionals

Higher-Order Functions 5 Functions that accept functions as arguments or return values. Functions in Lisp are first-class objects. Can be created at run-time, passed as arguments, returned as values, stored in variables... just like any other type of data.? (defun filter (list test) (cond ((null list) nil) ((funcall test (first list)) (cons (first list) (filter (rest list) test))) (t (filter (rest list) test))))? (defparameter foo (11 22 33 44 55))? (filter foo # evenp) (22 44) Functions, recursion, conditionals, predicates

Higher-Order Functions 5 Functions that accept functions as arguments or return values. Functions in Lisp are first-class objects. Can be created at run-time, passed as arguments, returned as values, stored in variables... just like any other type of data.? (defun filter (list test) (cond ((null list) nil) ((funcall test (first list)) (cons (first list) (filter (rest list) test))) (t (filter (rest list) test))))? (defparameter foo (11 22 33 44 55))? (filter foo # evenp) (22 44) Functions, recursion, conditionals, predicates, lists for code and data.

Anonymous Functions 6 We can also pass function arguments without first binding them to a name, using lambda expressions: (lambda (parameters) body) A function definition without the defun and symbol part.? (filter foo # (lambda (x) (and (> x 20) (< x 50)))) (22 33 44)

Anonymous Functions 6 We can also pass function arguments without first binding them to a name, using lambda expressions: (lambda (parameters) body) A function definition without the defun and symbol part.? (filter foo # (lambda (x) (and (> x 20) (< x 50)))) (22 33 44) Typically used for ad-hoc functions that are only locally relevant and simple enough to be expressed inline.

Anonymous Functions 6 We can also pass function arguments without first binding them to a name, using lambda expressions: (lambda (parameters) body) A function definition without the defun and symbol part.? (filter foo # (lambda (x) (and (> x 20) (< x 50)))) (22 33 44) Typically used for ad-hoc functions that are only locally relevant and simple enough to be expressed inline. Or, when constructing functions as return values.

Returning Functions 7 We have seen how to create anonymous functions using lambda and pass them as arguments. So we can combine that with a function that itself returns another function (which we then bind to a variable).

Returning Functions 7 We have seen how to create anonymous functions using lambda and pass them as arguments. So we can combine that with a function that itself returns another function (which we then bind to a variable).? (defparameter foo (11 22 33 44 55))? (defun make-range-test (lower upper) # (lambda (x) (and (> x lower) (< x upper))))

Returning Functions 7 We have seen how to create anonymous functions using lambda and pass them as arguments. So we can combine that with a function that itself returns another function (which we then bind to a variable).? (defparameter foo (11 22 33 44 55))? (defun make-range-test (lower upper) # (lambda (x) (and (> x lower) (< x upper))))? (filter foo (make-range-test 10 30)) (11 22)

Parameter Lists: Variable Arities and Naming 8 Optional Parameters? (defun foo (x &optional y (z 42)) (list x y z))? (foo 1) (1 nil 42)? (foo 1 2 3) (1 2 3)

Parameter Lists: Variable Arities and Naming 8 Optional Parameters? (defun foo (x &optional y (z 42)) (list x y z)) Keyword Parameters? (defun foo (x &key y (z 42)) (list x y z))? (foo 1) (1 nil 42)? (foo 1 2 3) (1 2 3)? (foo 1) (1 nil 42)? (foo 1 :z 3 :y 2) (1 2 3)

Parameter Lists: Variable Arities and Naming 8 Optional Parameters? (defun foo (x &optional y (z 42)) (list x y z)) Keyword Parameters? (defun foo (x &key y (z 42)) (list x y z))? (foo 1) (1 nil 42)? (foo 1 2 3) (1 2 3)? (foo 1) (1 nil 42)? (foo 1 :z 3 :y 2) (1 2 3) Rest Parameters? (defun avg (x &rest rest) (let ((numbers (cons x rest))) (/ (apply # + numbers) (length numbers))))? (avg 3) 3? (avg 1 2 3 4 5 6 7) 4

Recap: Equality for One and All 9 eq tests object identity; it is not useful for numbers or characters. eql is like eq, but well-defined on numbers and characters. equal tests structural equivalence equalp is like equal but insensitive to case and numeric type.

Recap: Equality for One and All 9 eq tests object identity; it is not useful for numbers or characters. eql is like eq, but well-defined on numbers and characters. equal tests structural equivalence equalp is like equal but insensitive to case and numeric type.? (eq (list 1 2 3) (1 2 3)) nil

Recap: Equality for One and All 9 eq tests object identity; it is not useful for numbers or characters. eql is like eq, but well-defined on numbers and characters. equal tests structural equivalence equalp is like equal but insensitive to case and numeric type.? (eq (list 1 2 3) (1 2 3)) nil? (equal (list 1 2 3) (1 2 3)) t

Recap: Equality for One and All 9 eq tests object identity; it is not useful for numbers or characters. eql is like eq, but well-defined on numbers and characters. equal tests structural equivalence equalp is like equal but insensitive to case and numeric type.? (eq (list 1 2 3) (1 2 3)) nil? (equal (list 1 2 3) (1 2 3)) t? (eq 42 42)? [implementation-dependent]

Recap: Equality for One and All 9 eq tests object identity; it is not useful for numbers or characters. eql is like eq, but well-defined on numbers and characters. equal tests structural equivalence equalp is like equal but insensitive to case and numeric type.? (eq (list 1 2 3) (1 2 3)) nil? (equal (list 1 2 3) (1 2 3)) t? (eq 42 42)? [implementation-dependent]? (eql 42 42) t

Recap: Equality for One and All 9 eq tests object identity; it is not useful for numbers or characters. eql is like eq, but well-defined on numbers and characters. equal tests structural equivalence equalp is like equal but insensitive to case and numeric type.? (eq (list 1 2 3) (1 2 3)) nil? (equal (list 1 2 3) (1 2 3)) t? (eq 42 42)? [implementation-dependent]? (eql 42 42) t? (eql 42 42.0) nil

Recap: Equality for One and All 9 eq tests object identity; it is not useful for numbers or characters. eql is like eq, but well-defined on numbers and characters. equal tests structural equivalence equalp is like equal but insensitive to case and numeric type.? (eq (list 1 2 3) (1 2 3)) nil? (equal (list 1 2 3) (1 2 3)) t? (eq 42 42)? [implementation-dependent]? (eql 42 42) t? (eql 42 42.0) nil? (equalp 42 42.0) t

Recap: Equality for One and All 9 eq tests object identity; it is not useful for numbers or characters. eql is like eq, but well-defined on numbers and characters. equal tests structural equivalence equalp is like equal but insensitive to case and numeric type.? (eq (list 1 2 3) (1 2 3)) nil? (equal (list 1 2 3) (1 2 3)) t? (eq 42 42)? [implementation-dependent]? (eql 42 42) t? (eql 42 42.0) nil? (equalp 42 42.0) t? (equal "foo" "foo") t

Recap: Equality for One and All 9 eq tests object identity; it is not useful for numbers or characters. eql is like eq, but well-defined on numbers and characters. equal tests structural equivalence equalp is like equal but insensitive to case and numeric type.? (eq (list 1 2 3) (1 2 3)) nil? (equal (list 1 2 3) (1 2 3)) t? (eq 42 42)? [implementation-dependent]? (eql 42 42) t? (eql 42 42.0) nil? (equalp 42 42.0) t? (equal "foo" "foo") t? (equalp "FOO" "foo") t

Recap: Equality for One and All 9 eq tests object identity; it is not useful for numbers or characters. eql is like eq, but well-defined on numbers and characters. equal tests structural equivalence equalp is like equal but insensitive to case and numeric type.? (eq (list 1 2 3) (1 2 3)) nil? (equal (list 1 2 3) (1 2 3)) t? (eq 42 42)? [implementation-dependent]? (eql 42 42) t? (eql 42 42.0) nil? (equalp 42 42.0) t? (equal "foo" "foo") t? (equalp "FOO" "foo") t Also many type-specialized tests like =, string=, etc.

Suggested Home Exercise 10 From the 2013 Final Exam Write two versions of a function swap; one based on recursion and one based on iteration. The function should take three parameters x, y and list where the goal is to replace every element matching x with y in the list list. Here is an example of the expected behavior:? (swap "foo" "bar" ("zap" "foo" "foo" "zap" "foo")) ("zap" "bar" "bar" "zap" "bar") Try to avoid using destructive operations if you can. [7 points]

A Brief Detour: Macros 11 Elevator Pitch: programs that generate programs. Macros provide a way for our code to manipulate itself (before it is passed to the compiler). Can implement transformations that extend the syntax of the language. Allows us to control (or even prevent) the evaluation of arguments. We have already encountered some built-in Common Lisp macros: and, or, if, cond, defun, setf, etc.

A Brief Detour: Macros 11 Elevator Pitch: programs that generate programs. Macros provide a way for our code to manipulate itself (before it is passed to the compiler). Can implement transformations that extend the syntax of the language. Allows us to control (or even prevent) the evaluation of arguments. We have already encountered some built-in Common Lisp macros: and, or, if, cond, defun, setf, etc. Although macro writing is out of the scope of this course, we will look at perhaps the best example of how macros can redefine the syntax of the language for good or for worse, depending on who you ask: loop

Iteration 12 While recursion is a powerful control structure, (let ((result nil)) (dolist (x (0 1 2 3 4 5)) (when (evenp x) (push x result))) (reverse result)) (0 2 4) sometimes iteration comes more natural. dolist and dotimes are fine for simple iteration.

Iteration 12 While recursion is a powerful control structure, sometimes iteration comes more natural. dolist and dotimes are fine for simple iteration. (let ((result nil)) (dolist (x (0 1 2 3 4 5)) (when (evenp x) (push x result))) (reverse result)) (0 2 4) (let ((result nil)) (dotimes (x 6) (when (evenp x) (push x result))) (reverse result)) (0 2 4)

Iteration While recursion is a powerful control structure, sometimes iteration comes more natural. dolist and dotimes are fine for simple iteration. But (the mighty) loop is much more general and versatile. (let ((result nil)) (dolist (x (0 1 2 3 4 5)) (when (evenp x) (push x result))) (reverse result)) (0 2 4) (let ((result nil)) (dotimes (x 6) (when (evenp x) (push x result))) (reverse result)) (0 2 4) (loop for x below 6 when (evenp x) collect x) (0 2 4) 12

Iteration with loop 13 (loop for i from 10 to 50 by 10 collect i) (10 20 30 40 50) Illustrates the power of syntax extension through macros; loop is basically a mini-language for iteration.

Iteration with loop 13 (loop for i from 10 to 50 by 10 collect i) (10 20 30 40 50) Illustrates the power of syntax extension through macros; loop is basically a mini-language for iteration. Reduced uniformity: different syntax based on special keywords. Paul Graham on loop: one of the worst flaws in Common Lisp.

Iteration with loop 13 (loop for i from 10 to 50 by 10 collect i) (10 20 30 40 50) Illustrates the power of syntax extension through macros; loop is basically a mini-language for iteration. Reduced uniformity: different syntax based on special keywords. Paul Graham on loop: one of the worst flaws in Common Lisp. But non-lispy as it may be, loop is extremely general and powerful!

loop: A Few More Examples 14? (loop for i below 10 when (oddp i) sum i) 25

loop: A Few More Examples 14? (loop for i below 10 when (oddp i) sum i) 25? (loop for x across "foo" collect x) (#\f #\o #\o)

loop: A Few More Examples 14? (loop for i below 10 when (oddp i) sum i) 25? (loop for x across "foo" collect x) (#\f #\o #\o)? (loop with foo = (a b c d) for i in foo for j from 0 until (eq i c) do (format t "~a: ~a ~%" j i)) 0: A 1: B

loop: Even More Examples 15? (loop for i below 10 if (evenp i) collect i into evens else collect i into odds finally (return (list evens odds))) ((0 2 4 6 8) (1 3 5 7 9))

loop: Even More Examples 15? (loop for i below 10 if (evenp i) collect i into evens else collect i into odds finally (return (list evens odds))) ((0 2 4 6 8) (1 3 5 7 9))? (loop for value being each hash-value of *dictionary* using (hash-key key) do (format t "~&~a -> ~a" key value))

loop: The Swiss Army Knife of Iteration 16 Iteration over lists or vectors: for symbol { in on across } list

loop: The Swiss Army Knife of Iteration 16 Iteration over lists or vectors: for symbol { in on across } list Counting through ranges: for symbol [ from number ] { to downto } number [ by number ]

loop: The Swiss Army Knife of Iteration 16 Iteration over lists or vectors: for symbol { in on across } list Counting through ranges: for symbol [ from number ] { to downto } number [ by number ] Iteration over hash tables: for symbol being each { hash-key hash-value } in hash table

loop: The Swiss Army Knife of Iteration 16 Iteration over lists or vectors: for symbol { in on across } list Counting through ranges: for symbol [ from number ] { to downto } number [ by number ] Iteration over hash tables: for symbol being each { hash-key hash-value } in hash table Stepwise computation: for symbol = sexp then sexp

loop: The Swiss Army Knife of Iteration 16 Iteration over lists or vectors: for symbol { in on across } list Counting through ranges: for symbol [ from number ] { to downto } number [ by number ] Iteration over hash tables: for symbol being each { hash-key hash-value } in hash table Stepwise computation: for symbol = sexp then sexp Accumulation: { collect append sum minimize count... } sexp

loop: The Swiss Army Knife of Iteration 16 Iteration over lists or vectors: for symbol { in on across } list Counting through ranges: for symbol [ from number ] { to downto } number [ by number ] Iteration over hash tables: for symbol being each { hash-key hash-value } in hash table Stepwise computation: for symbol = sexp then sexp Accumulation: { collect append sum minimize count... } sexp Control: { while until repeat when unless... } sexp

loop: The Swiss Army Knife of Iteration 16 Iteration over lists or vectors: for symbol { in on across } list Counting through ranges: for symbol [ from number ] { to downto } number [ by number ] Iteration over hash tables: for symbol being each { hash-key hash-value } in hash table Stepwise computation: for symbol = sexp then sexp Accumulation: { collect append sum minimize count... } sexp Control: { while until repeat when unless... } sexp Local variables: with symbol = sexp

loop: The Swiss Army Knife of Iteration 16 Iteration over lists or vectors: for symbol { in on across } list Counting through ranges: for symbol [ from number ] { to downto } number [ by number ] Iteration over hash tables: for symbol being each { hash-key hash-value } in hash table Stepwise computation: for symbol = sexp then sexp Accumulation: { collect append sum minimize count... } sexp Control: { while until repeat when unless... } sexp Local variables: with symbol = sexp Initialization and finalization: { initially finally } sexp +

loop: The Swiss Army Knife of Iteration 16 Iteration over lists or vectors: for symbol { in on across } list Counting through ranges: for symbol [ from number ] { to downto } number [ by number ] Iteration over hash tables: for symbol being each { hash-key hash-value } in hash table Stepwise computation: for symbol = sexp then sexp Accumulation: { collect append sum minimize count... } sexp Control: { while until repeat when unless... } sexp Local variables: with symbol = sexp Initialization and finalization: { initially finally } sexp + All of these can be combined freely, e.g. iterating through a list, counting a range, and stepwise computation, all in parallel.

loop: The Swiss Army Knife of Iteration 16 Iteration over lists or vectors: for symbol { in on across } list Counting through ranges: for symbol [ from number ] { to downto } number [ by number ] Iteration over hash tables: for symbol being each { hash-key hash-value } in hash table Stepwise computation: for symbol = sexp then sexp Accumulation: { collect append sum minimize count... } sexp Control: { while until repeat when unless... } sexp Local variables: with symbol = sexp Initialization and finalization: { initially finally } sexp + All of these can be combined freely, e.g. iterating through a list, counting a range, and stepwise computation, all in parallel. Note: without at least one accumulator, loop will only return nil.

Input and Output 17 Reading and writing is mediated through streams. The symbol t indicates the default stream, the terminal.? (format t "~a is the ~a.~%" 42 "answer") 42 is the answer. nil

Input and Output 17 Reading and writing is mediated through streams. The symbol t indicates the default stream, the terminal.? (format t "~a is the ~a.~%" 42 "answer") 42 is the answer. nil (read-line stream nil) reads one line of text from stream, returning it as a string. (read stream nil) reads one well-formed s-expression. The second reader argument asks to return nil on end-of-file.

Input and Output 17 Reading and writing is mediated through streams. The symbol t indicates the default stream, the terminal.? (format t "~a is the ~a.~%" 42 "answer") 42 is the answer. nil (read-line stream nil) reads one line of text from stream, returning it as a string. (read stream nil) reads one well-formed s-expression. The second reader argument asks to return nil on end-of-file. (with-open-file (stream "sample.txt" :direction :input) (loop for line = (read-line stream nil) while line do (format t "~a~%" line)))

More Data Structures: Arrays 18 Integer-indexed container (indices count from zero)? (setf array (make-array 5)) #(nil nil nil nil nil)? (setf (aref array 0) 42) 42? array #(42 nil nil nil nil)

More Data Structures: Arrays 18 Integer-indexed container (indices count from zero)? (setf array (make-array 5)) #(nil nil nil nil nil)? (setf (aref array 0) 42) 42? array #(42 nil nil nil nil) Can be fixed-sized (default) or dynamically adjustable. Can also represent grids of multiple dimensions:? (defparameter array (make-array (2 5) :initial-element 0)) #((0 0 0 0 0) (0 0 0 0 0))? (incf (aref array 1 2)) 1 0 1 2 3 4 0 0 0 0 0 0 1 0 0 1 0 0

Arrays: Specializations and Generalizations 19 Vectors specialized type of arrays: one-dimensional. Strings specialized type of vectors (similarly: bit vectors). Vectors and lists are subtypes of the abstract data type sequence. Large number of built-in sequence functions, e.g.:

Arrays: Specializations and Generalizations 19 Vectors specialized type of arrays: one-dimensional. Strings specialized type of vectors (similarly: bit vectors). Vectors and lists are subtypes of the abstract data type sequence. Large number of built-in sequence functions, e.g.:? (length "foo") 3

Arrays: Specializations and Generalizations 19 Vectors specialized type of arrays: one-dimensional. Strings specialized type of vectors (similarly: bit vectors). Vectors and lists are subtypes of the abstract data type sequence. Large number of built-in sequence functions, e.g.:? (length "foo") 3? (elt "foo" 0) #\f

Arrays: Specializations and Generalizations 19 Vectors specialized type of arrays: one-dimensional. Strings specialized type of vectors (similarly: bit vectors). Vectors and lists are subtypes of the abstract data type sequence. Large number of built-in sequence functions, e.g.:? (length "foo") 3? (elt "foo" 0) #\f? (count-if # numberp (1 a "2" 3 (b)))

Arrays: Specializations and Generalizations 19 Vectors specialized type of arrays: one-dimensional. Strings specialized type of vectors (similarly: bit vectors). Vectors and lists are subtypes of the abstract data type sequence. Large number of built-in sequence functions, e.g.:? (length "foo") 3? (elt "foo" 0) #\f? (count-if # numberp (1 a "2" 3 (b))) 2

Arrays: Specializations and Generalizations 19 Vectors specialized type of arrays: one-dimensional. Strings specialized type of vectors (similarly: bit vectors). Vectors and lists are subtypes of the abstract data type sequence. Large number of built-in sequence functions, e.g.:? (length "foo") 3? (elt "foo" 0) #\f? (count-if # numberp (1 a "2" 3 (b))) 2? (subseq "foobar" 3 6) "bar"

Arrays: Specializations and Generalizations 19 Vectors specialized type of arrays: one-dimensional. Strings specialized type of vectors (similarly: bit vectors). Vectors and lists are subtypes of the abstract data type sequence. Large number of built-in sequence functions, e.g.:? (length "foo") 3? (elt "foo" 0) #\f? (count-if # numberp (1 a "2" 3 (b))) 2? (subseq "foobar" 3 6) "bar"? (substitute #\a #\o "hoho") "haha"

Arrays: Specializations and Generalizations 19 Vectors specialized type of arrays: one-dimensional. Strings specialized type of vectors (similarly: bit vectors). Vectors and lists are subtypes of the abstract data type sequence. Large number of built-in sequence functions, e.g.:? (length "foo") 3? (elt "foo" 0) #\f? (count-if # numberp (1 a "2" 3 (b))) 2? (subseq "foobar" 3 6) "bar"? (substitute #\a #\o "hoho") "haha"? (remove a (a b b a)) (b b)

Arrays: Specializations and Generalizations 19 Vectors specialized type of arrays: one-dimensional. Strings specialized type of vectors (similarly: bit vectors). Vectors and lists are subtypes of the abstract data type sequence. Large number of built-in sequence functions, e.g.:? (length "foo") 3? (elt "foo" 0) #\f? (count-if # numberp (1 a "2" 3 (b))) 2? (subseq "foobar" 3 6) "bar"? (substitute #\a #\o "hoho") "haha"? (remove a (a b b a)) (b b)? (some # listp (1 a "2" 3 (b)))

Arrays: Specializations and Generalizations 19 Vectors specialized type of arrays: one-dimensional. Strings specialized type of vectors (similarly: bit vectors). Vectors and lists are subtypes of the abstract data type sequence. Large number of built-in sequence functions, e.g.:? (length "foo") 3? (elt "foo" 0) #\f? (count-if # numberp (1 a "2" 3 (b))) 2? (subseq "foobar" 3 6) "bar"? (substitute #\a #\o "hoho") "haha"? (remove a (a b b a)) (b b)? (some # listp (1 a "2" 3 (b))) T

Arrays: Specializations and Generalizations 19 Vectors specialized type of arrays: one-dimensional. Strings specialized type of vectors (similarly: bit vectors). Vectors and lists are subtypes of the abstract data type sequence. Large number of built-in sequence functions, e.g.:? (length "foo") 3? (elt "foo" 0) #\f? (count-if # numberp (1 a "2" 3 (b))) 2? (subseq "foobar" 3 6) "bar"? (substitute #\a #\o "hoho") "haha"? (remove a (a b b a)) (b b)? (some # listp (1 a "2" 3 (b)))? (sort (1 2 1 3 1 0) # <) (0 1 1 1 2 3)

Arrays: Specializations and Generalizations 19 Vectors specialized type of arrays: one-dimensional. Strings specialized type of vectors (similarly: bit vectors). Vectors and lists are subtypes of the abstract data type sequence. Large number of built-in sequence functions, e.g.:? (length "foo") 3? (elt "foo" 0) #\f? (count-if # numberp (1 a "2" 3 (b))) 2? (subseq "foobar" 3 6) "bar"? (substitute #\a #\o "hoho") "haha"? (remove a (a b b a)) (b b)? (some # listp (1 a "2" 3 (b)))? (sort (1 2 1 3 1 0) # <) (0 1 1 1 2 3) Others: position, every, count, remove-if, find, merge, map, reverse, concatenate, reduce,...

In Conclusion 20 http://xkcd.com/297/

More Practically: Programming in INF4820 21 In the IFI Linux environment, we have available Allegro Common Lisp, a commercial Lisp interpreter and compiler. We provide a pre-configured, integrated setup with emacs and the SLIME Lisp interaction mode. First-time users, please spend some time studying basic keyboard commands, for example: C-h t and M-x doctor RET. Several open-source Lisp implementation exist, e.g. Clozure or SBCL, compatible with SLIME, so feel free to experiment (on your own time). We have posted a Getting Started guide and Emacs Cheat Sheet on the course pages last week.

Good Lisp Style 22 Bottom-Up Design Instead of trying to solve everything with one large function: Build your program with layers of smaller functions. Eliminate repetition and patterns. Related; define abstraction barriers. Separate the code that uses a given data abstraction from the code that implement that data abstraction. Promotes code re-use: Makes the code shorter and easier to read, debug and maintain.

Good Lisp Style 22 Bottom-Up Design Instead of trying to solve everything with one large function: Build your program with layers of smaller functions. Eliminate repetition and patterns. Related; define abstraction barriers. Separate the code that uses a given data abstraction from the code that implement that data abstraction. Promotes code re-use: Makes the code shorter and easier to read, debug and maintain. Somewhat more mundane: Adhere to the time-honored 80 column rule. Close multiple parens on the same line. Use auto-indentation (TAB) in Emacs.

If you can t see the forest for the trees... 23... or can t even see the trees for the parentheses. A Lisp specialty: Uniformity Lisp beginners can sometimes find the syntax overwhelming. What s with all the parentheses? For seasoned Lispers the beauty lies in the fact that there s hardly any syntax at all (beyond the abstract data type of lists). Lisp code is a Lisp data structure. Lisp programs are trees of sexps (comparable to the abstract syntax trees created internally by the parser/compiler for other languages). Makes it easier to write code that generates code: macros.

Next week 24 Can we automatically infer the meaning of words? Distributional semantics Vector spaces: Spatial models for representing data Semantic spaces