Lisp A functional language
As always… How is it similar? First it runs on the same OS as all applications Uses runtime activation stack as others Needs sequence/selection/iteration Needs organization/procedures Just not obvious where these things are
Fundamentals First, everything is a list Second there are a few important fundamentals/operations to grasp Third it is fundamentally recursive (as are lists.. they have sublists) It is functional not procedural. Everything is viewed as either defining or invoking functions
A Lisp List ( A B C D) bounded by parenthesesseparated by spaces
A Lisp List ( A B C D) Lists are composed of atoms OR sublists ( (A) B (C D))
Basic Operations use PREFIX notation operator precedes operands ( ) Abs(x) operator operand
Other simple examples ( ) ( ) ( + 2 – 7 4 ) (7-4)=5
Prefix notation simplifies Prefix looks more complicated …BUT Think about precedence and associativity It’s NOT relevant to prefix format No precedence or associativity rules
Prefix notation simplifies (– + / * 2 2 ) In lisp In standard algebra ( 10 / – 2 * 2 ) Need to know precedence rules No rules to know … Well, use a single stack, push each operator or operand, Evaluate whenever two operands on the top. Example on next slide.
Prefix notation simplifies (– + / * 2 2 ) – ( + / * 2 2 ) + – ( / * 2 2 ) / + – ( * 2 2 ) 10 / + – (5 7 * 2 2 ) 5 10 / + – 2 + – – (7 * 2 2 ) 9 – (* 2 2 ) * 9 – (2 2 ) 2 * 9 – (2)(2) 2 2 * 9 – () 4 9 – 5 Shows where 2 operands on top… evaluate!
Expressions Substitute one algorithm that is new for all associativity and precedence rules Granted it is odd at this point. Only emphasizing the that precedence are a consequence of infix notation. Not absolutely necessary in all notations. –Like postfix or prefix and variations
Main Lisp list functions car -> returns first element in the list cdr -> returns all but the first element in the list
Main Lisp list functions ( car ( A B C D)) = A (car ( (A) B (C D))) = (A) ( cdr ( A B C D)) = ( B C D) (cdr ( (A) B (C D))) = (B (C D))
You know to Do expressions Call and evaluate functions Do some simple list functions How about –Selection –Iteration
Selection if (a > b) return 1 else if ( c > d) return 2 else if ( e > f) return 3 else return 4 ( cond ( ( > a b ) 1) ( ( > c d ) 2 ) ( ( > e f ) 3 ) ( ELSE 4) ) In lisp
Iteration Use recursion Before seeing recursion –Learn how to define a function –Learn how to define a recursive function
Defining a function ( adding two integers) ( define ( Add x y ) ( + x y ) ) Add (x, y) { return x + y; } In lisp Works for two simple atoms, but what about lists? You need recursion!
Iteration ( define ( Addup a ) ( cond ((NULL? a) 0) (ELSE (+ (car a) (Addup (cdr a)))) ) int Addup (a,n) { sum=0; for (i=0, i<n; i++) sum+= a[i]; return sum; } in lisp Summing elements in a list(table) Note: if the list is nested, ( 1 ( 2 3 ) 4), this Addup will not work! int Addup (a,n) { sum=0; if (n==1) return a[0]; else return a[0]+Addup(a[1],n-1) } Recursively in c