return total def cube(k): return pow(k, 3) >>> summation(5, cube) 225 """ total, k = 0, 1 while k <= n:

Size: px
Start display at page:

Download "return total def cube(k): return pow(k, 3) >>> summation(5, cube) 225 """ total, k = 0, 1 while k <= n:"

Transcription

1 CS 6A Midterm Study Guide Page Import statement mul(add(, mul(, 6)), add(, 5)) Pure Functions - abs(number): Assignment statement Name Binding Value mul 6 add(, mul(, 6)) add(, 5), (x, y): Code (left): Statements and s Red arrow points to next line. Gray arrow points to the line just executed Frames (right): A name is bound to a value In a frame, there is at most one binding per name add mul(, 6) add 5 Non-Pure Functions - print(): None mul 6 display - Intrinsic name of function called Formal parameter bound to argument Local frame Return value is not a binding! Built-in function User-defined function Defining: Def statement >>> def Call : Formal parameter square( x ): return mul(x, x) Body square(+) operator: square function: func square(x) Return (return statement) operand: + argument: Compound statement Clause <header>: <statement> <statement> Suite <separating header>: <statement> <statement> def abs_value(x): A name evaluates to the value bound to that name in the earliest frame of the current environment in which that name is found. Calling/Applying: Argument Intrinsic name square( x ): return mul(x, x) y is not found Error Return value 6 statement, clauses, headers, suites, boolean contexts if x > : return x elif x == : return return -x Evaluation rule for call s:.evaluate the operator and operand subs..apply the function that is the value of the operator sub to the arguments that are the values of the operand subs. Applying user-defined functions:.create a new local frame with the same parent as the function that was applied..bind the arguments to the functions formal parameter names in that frame..execute the body of the function in the environment beginning at that frame. Execution rule for def statements:.create a new function value with the specified name, formal parameters, and function body..its parent is the frame of the current environment..bind the name of the function to the function value in the frame of the current environment. Execution rule for assignment statements:.evaluate the (s) on the right of the equal sign..simultaneously bind the names on the left to those values, in the frame of the current environment. Execution rule for conditional statements: Each clause is considered in order..evaluate the headers..if it is a true value, execute the suite, then skip the remaining clauses in the statement. Evaluation rule for or s:.evaluate the sub <left>..if the result is a true value v, then the evaluates to v..otherwise, the evaluates to the value of the sub <right>. Evaluation rule for and s:.evaluate the sub <left>..if the result is a false value v, then the evaluates to v..otherwise, the evaluates to the value of the sub <right>. Evaluation rule for not s:.evaluate <exp>; The value is if the result is a false value, and otherwise. Execution rule for while statements:. Evaluate the header s.. If it is a true value, execute the (whole) suite, then return to step. A y is not found A call and the body of the function being called are evaluated in different environments def cube(k): return (k, ) def summation(n, term): will be bound to a function Sum the n terms of a sequence. >>> summation(5, cube) 5 total, k =, while k <= n: Function of a single argument (not called term) A formal parameter that The cube function is passed as an argument value total, k = total + term(k), k + return total B def fib(n): Compute the nth Fibonacci number, for N >=. pred, curr =, # Zeroth and Fibonacci numbers k = # curr is the kth Fibonacci number while k < n: pred, curr = curr, pred + curr k = k + return curr A B The function bound to term gets called here An environment is a sequence of frames An environment for a non-nested function (no def within def) consists of one local frame, followed by the global frame Nested def statements: Functions defined within other function bodies are bound to names in the local frame Higher-order function: A function that takes a function as an argument value or returns a function as a return value

2 CS 6A Midterm Study Guide Page square = lambda x,y: x * y A function A function that returns a function def make_adder(n): Return a function that takes one argument k and returns k + n. >>> add_three = make_adder() >>> add_three() 7 def adder(k): return k + n return adder with formal parameters x and y that returns the value of "x * y" Must be a single A local def statement Every user-defined function has a parent frame (often global) The parent of a function is the frame in which it was defined Every local frame has a parent frame (often global) The parent of a frame is the parent of the function called Nested def Evaluates to a function. No "return" keyword! Can refer to names in the enclosing function The name add_three is bound to a function def compose(f, g): Return a function h that composes f and g. >>> compose(square, make_adder())() 5 def h(x): return f(g(x)) return h Anatomy of a recursive function: The def statement header is similar to other functions Conditional statements check for base cases Base cases are evaluated without recursive calls Recursive cases are evaluated with recursive calls def sum_digits(n): Return the sum of the digits of positive integer n. if n < : return n all_but_last, last = n //, n % return sum_digits(all_but_last) + last A function s signature has all the information to create a local frame Return value of make_adder is an argument to compose square = lambda x: x * x VS def square(x): return x * x Both create a function with the same domain, range, and behavior. Both functions have as their parent the environment in which they were defined. Both bind that function to the name square. Only the def statement gives the function an intrinsic name. When a function is defined:. Create a function value: func <name>(<formal parameters>). Its parent is the current frame.. Bind <name> to the function value in the current frame (which is the frame of the current environment). When a function is called:. Add a local frame, titled with the <name> of the function being called.. Copy the parent of the function to the local frame: [parent=<label>]. Bind the <formal parameters> to the arguments in the local frame.. Execute the body of the function in the environment that starts with the local frame. Lists: >>> digits = [,,, ] >>> len(digits) >>> digits[] digits >>> [, 7] + digits * [, 7,,,,,,,, ] >>> pairs = [[, ], [, ]] >>> pairs[] [, ] pairs >>> pairs[][] List comprehensions: [<map exp> for <name> in <iter exp> if <filter exp>] Short version: [<map exp> for <name> in <iter exp>] For statement: Slicing: >>> digits[:] [, ] >>> digits[:] [,, ] Slicing creates a new object for <name> in <>: <suite> Membership: >>> digits = [,,, ] >>> in digits >>> not in digits Strings as sequences: >>> city=berkeley >>> len(city) >>> city[] k >>> UC+city >>> here in "Wheres Waldo?" UCBerkeley >>> in [,,,, 5] >>> [,, ] in [,,, ] def inverse_cascade(n): grow(n) print(n) shrink(n) def f_then_g(f, g, n): if n: f(n) g(n) Each cascade frame is from a different call to cascade. Until the Return value appears, that call has not completed. Any statement can appear before or after the recursive call.,,,,, 5, 6, 7,, def fib(n): if n == : return elif n == : return return fib(n-) + fib(n-) grow = lambda n: f_then_g(grow, print, n//) shrink = lambda n: f_then_g(print, shrink, n//) n: fib(n):,,,,, 5,,,, Recursive decomposition: finding simpler instances of a problem. E.g., count_partitions(6, ) Explore two possibilities: Use at least one Dont use any Solve two simpler problems: count_partitions(, ) count_partitions(6, ) Tree recursion often involves exploring different choices. from operator import floordiv, mod def divide_exact(n, d): Return the quotient and remainder of dividing N by D. >>> q, r = divide_exact(, ) >>> q >>> r return floordiv(n, d), mod(n, d) def count_partitions(n, m): if n == : return elif n < : return elif m == : return with_m = count_partitions(n-m, m) without_m = count_partitions(n, m-) return with_m + without_m Multiple assignment to two names Multiple return values, separated by commas

3 CS 6A Midterm Study Guide Page Numeric types in Python: >>> type() <class int> List comprehensions: [<map exp> for <name> in <iter exp> if <filter Represents integers exactly >>> type(.5) <class float> Short version: [<map exp> for <name> in <iter Represents real numbers approximately >>> type(+j) <class complex> Rational implementation using functions: def rational(n, d): def select(name): if name == n: return n elif name == d: return d return select List & dictionary mutation: A combined that evaluates to a list using this evaluation procedure:. Add a new frame with the current frame as its parent. Create an empty result list that is the value of the. For each element in the iterable value of <iter exp>: A. Bind <name> to that element in the new frame from step B. If <filter exp> evaluates to a true value, then add This function represents a rational number The result of calling repr on a value is what Python prints in an interactive session The result of calling str on a value is what Python prints using the print function >>> e. >>> print(repr(e)). Constructor is a higher-order function >>> print(today) -- str and repr are both polymorphic; they apply to any object repr invokes a zero-argument method repr on its argument def numer(x): return x(n) Selector calls x def denom(x): return x(d) >>> today. repr () datetime.date(,, ) >>> today. str () -- def memo(f): cache = {} def memoized(n): if n not in cache: cache[n] = f(n) return cache[n] return memoized Memoization: fib(5) Lists: >>> digits = [,,, ] >>> len(digits) digits >>> digits[] fib() fib() fib() fib() >>> [, 7] + digits * [, 7,,,,,,,, ] fib() fib() >>> list(range()) [,,, ] k f (n) R(n) Quadratic growth. E.g., overlap Incrementing n increases R(n) by the problem size n You can copy a list by calling the list constructor or slicing the list from the beginning to the end. (n) (log n) Linear growth. Logarithmic growth. E.g., exp_fast Constants: Constant terms do not affect the order of growth of a process Doubling the problem only increments R(n) Constant. The problem size doesnt matter Logarithms: The base of a logarithm does not affect the order of growth of a process () ) Membership: Slicing: >>> digits = [,,, ] >>> digits[:] [, ] >>> in digits >>> digits[:] [,, ] >>> not in digits Slicing creates a new object Recursive fib takes steps, where + 5 =.6 E.g., factors or exp (n) (log n) The parent frame contains the balance of withdraw List constructor Range with a starting value >>> suits = [coin, string, myriad] >>> suits.pop() Remove and return myriad the last element >>> suits.remove(string) Remove a value >>> suits.append(cup) >>> suits.extend([sword, club]) >>> suits[] = spade Add all >>> suits values [coin, cup, spade, club] Replace a >>> suits[:] = [diamond] slice with >>> suits values [diamond, spade, club] >>> suits.insert(, heart) Add an element at an index >>> suits [heart, diamond, spade, club] (n ) ( n Length: ending value - starting value Element selection: starting value + index >>> list(range(-, )) [-, -,, ] Exponential growth. Every call decreases the same balance range(-, ) fib() >>> nums = {I:., V: 5, X: } >>> nums[x] >>> nums[i] = >>> nums[l] = 5 >>> nums {X:, L: 5, V: 5, I: } >>> sum(nums.values()) 66 >>> dict([(, 9), (, 6), (5, 5)]) {: 9, : 6, 5: 5} >>> nums.get(a, ) >>> nums.get(v, ) 5 >>> {x: x*x for x in range(,6)} {: 9, : 6, 5: 5} Incrementing the problem scales R(n) by a factor (bn ) >>> for x, y in pairs: if x == y: same_count = same_count +, -, -, -,,,,,, fib() >>> a = [] >>> b = [] >>> b.append() >>> a [] >>> b [, ] Identity: <exp> is <exp> evaluates to if both <exp> and <exp> evaluate to the same object Equality: <exp> == <exp> evaluates to if both <exp> and <exp> evaluate to equal values Identical objects are always equal values A name for each element in a fixed-length sequence >>> same_count fib() Type dispatching: Look up a cross-type implementation of an operation based on the types of its arguments Type coercion: Look up a function for converting one type to another, then apply a type-specific implementation. for all n larger than some m >>> pairs=[[, ], [, ], [, ], [, ]] >>> same_count = fib() Skipped k f (n) A sequence of fixed-length sequences fib() Found in cache means that there are positive constants k and k such that Unpacking in a for statement: fib() fib() Call to fib (f (n)) Executing a for statement: for <name> in <>: <suite>. Evaluate the header <>, which must yield an iterable value (a sequence). For each element in that sequence, in order: A. Bind <name> to that element in the current frame B. Execute the <suite> R(n) = >>> pairs = [[, ], [, ]] >>> pairs[] [, ] pairs >>> pairs[][] fib() >>> a = [] >>> b = a >>> a.append() >>> a [, ] >>> b [, ] Strings as sequences: >>> city = Berkeley >>> len(city) >>> city[] k >>> here in "Wheres Waldo?" >>> in [,,,, 5] >>> [,, ] in [,,, ] (5 n) (log n) ( n) 5 (ln n) Nesting: When an inner process is repeated for each step in an outer process,multiply the steps in the outer and inner processes >>> withdraw = make_withdraw() to find the total number of steps >>> withdraw(5) def overlap(a, b): 75 count = Outer: length of a >>> withdraw(5) for item in a: 5 if item in b: def make_withdraw(balance): count += Inner: length of b def withdraw(amount): return count nonlocal balance If a and b are both length n, if amount > balance: then overlap takes (n ) steps return No funds balance = balance - amount Lower-order terms: The fastest-growing part of the computation dominates the total return balance return withdraw (n ) (n + n) (n + 5 n + log n + ) Status x = No nonlocal statement "x" is not bound locally Effect Create a new binding from name "x" to number in the frame of the current environment No nonlocal statement "x" is bound locally nonlocal x "x" is bound in Re-bind name "x" to object in the frame of the current environment a non-local frame nonlocal x "x" is not bound in a non-local frame nonlocal x "x" is bound in a non-local frame "x" also bound locally Re-bind "x" to in the non-local frame of the current environment in which "x" is bound SyntaxError: no binding for nonlocal x found SyntaxError: name x is parameter and nonlocal

4 CS 6A Midterm Study Guide Page Tree data abstraction: Leaf Root A tree has a root value and a sequence of branches; each branch is a tree class Tree: def init (self, label, children=()): self.label = label self.children = list(children) 5 Sub-tree def tree(root, branches=[]): for branch in branches: Verifies the tree definition assert is_tree(branch) return [root] + list(branches) def root(tree): return tree[] def branches(tree): return tree[:] class Link: def init (self,, rest=none): if rest == None: rest = Link.empty self. = Sequence abstraction special names: self.rest = rest def getitem (self, i): if i == : return self. return self.rest[i-] getitem len Element selection [] Built-in len function def len (self): return + len(self.rest) Yes, this call is recursive def repr (self): # Not Shown Creates a list from a sequence of branches Verifies that tree is bound to a list def is_tree(tree): if type(tree)!= list or len(tree) < : return for branch in branches(tree): if not is_tree(branch): return return def is_leaf(tree): return not branches(tree) def leaves(tree): The leaf values in tree. Node Branch >>> tree(, [tree(), tree(, [tree(), tree()])]) [, [], [, [], []]] def fib_tree(n): if n == or n == : return tree(n) left = fib_tree(n-), right = fib_tree(n-) fib_n = root(left) + root(right) return tree(fib_n, [left, right]) >>> leaves(fib_tree(5)) [,,,,,,, ] if is_leaf(tree): return [root(tree)] return sum([leaves(b) for b in branches(tree)], []) def is_leaf(self): def fib_tree(n): return not self.children if n == or n == : return Tree(n) def leaves(tree): left = fib_tree(n- ) if tree.is_leaf(): right = fib_tree(n- ) return [tree.label] fib_n = left.label+right.label return Tree(fib_n,[left, right]) return sum([leaves(b) for b in tree.children], []) class EmptyLink(Link): def init (self): pass Link.empty = EmptyLink() def extend_link(s, t): Return a Link with the elements of s followed by those of t. if s is Link.empty: return t return Link(s., extend_link(s.rest, t)) def map_link(f, s): if s is Link.empty: return s return Link(f(s.), map_link(f, s.rest)) Contents of the repr string of a Link instance >>> s = Link(, Link()) >>> extend_link(s, s) Link(, Link(, Link(, Link()))) >>> square = lambda x: x * x >>> map_link(square, s) Link(9, Link(6)) Python object system: Idea: All bank accounts have a balance and an account holder; the Account class should add those attributes to each of its instances A new instance is created by calling a class >>> a = Account(Jim) >>> a.holder Jim >>> a.balance An account instance When a class is called: balance: holder: Jim.A new instance of that class is created:.the init method of the class is called with the new object as its argument (named self), along with any additional arguments provided in the call. init is called a constructor self should always be bound to an instance of the Account class or a subclass of Account Function call: all arguments within parentheses Method invokation: One object before the dot and other arguments within parentheses class Account: def init (self, account_holder): self.balance = self.holder = account_holder def deposit(self, amount): self.balance = self.balance + amount return self.balance def withdraw(self, amount): if amount > self.balance: return Insufficient funds self.balance = self.balance - amount return self.balance >>> type(account.deposit) <class function> >>> type(a.deposit) <class method> >>> Account.deposit(a, 5) >>> a.deposit() Dot Call <>. <name> The <> can be any valid Python. The <name> must be a simple name. Evaluates to the value of the attribute looked up by <name> in the object that is the value of the <>. To evaluate a dot :. Evaluate the <> to the left of the dot, which yields the object of the dot. <name> is matched against the instance attributes of that object; if an attribute with that name exists, its value is returned. If not, <name> is looked up in the class, which yields a class attribute value. That value is returned unless it is a function, in which case a bound method is returned instead Assignment statements with a dot on their left-hand side affect attributes for the object of that dot If the object is an instance, then assignment sets an instance attribute If the object is a class, then assignment sets a class attribute Instance attributes of jim_account Account class attributes balance: holder: Jim interest:. >>> jim_account = Account(Jim) >>> tom_account = Account(Tom).. >>> Account.interest =... class CheckingAccount(Account): A bank account that charges for withdrawals. withdraw_fee = interest =. def withdraw(self, amount): return Account.withdraw(self, amount + self.withdraw_fee) return super().withdraw( interest:...5 (withdraw, deposit, init ) or Instance attributes of tom_account balance: holder: Tom =... >>> Account.interest =.5.5. amount + self.withdraw_fee) To look up a name in a class:. If it names an attribute in the class, return the attribute value.. Otherwise, look up the name in the base class, if there is one. >>> ch = CheckingAccount(Tom) # Calls Account. init >>> ch.interest # Found in CheckingAccount. >>> ch.deposit() # Found in Account >>> ch.withdraw(5) # Found in CheckingAccount

5 CS 6A Final Exam Study Guide Page Exceptions are raised with a raise statement. raise <> <> must evaluate to a subclass of BaseException or an instance of one. Exceptions are constructed like any other object. E.g., TypeError(Bad argument!) try: <try suite> except <exception class> as <name>: <except suite> The <try suite> is executed. If, during the course of executing the <try suite>, an exception is raised that is not handled otherwise, and If the class of the exception inherits from <exception class>, then The <except suite> is executed, with <name> bound to the exception. >>> try: x = / except ZeroDivisionError as e: print(handling a, type(e)) x = handling a <class ZeroDivisionError> >>> x for <name> in <>: <suite>. Evaluate the header <>, which yields an iterable object.. For each element in that sequence, in order: A. Bind <name> to that element in the frame of the current environment. B. Execute the <suite>. An iterable object has a method iter that returns an iterator. >>> counts = [,, ] >>> for item in counts: print(item) sum(s): map(f, s): filter(f, s): Return the sum of all elements x in s >>> items = counts. iter () >>> try: while : item = items. next () print(item) except StopIteration: pass Return an iterator yielding f(x) for all x in s Return an iterator yielding x in s for which f(x) is true def reduce(f, s, initial): Combine elements of s pairwise using f, starting with initial. >>> reduce(mul, [,, ], ) 6 for x in s: initial = f(initial, x) return initial A stream is a linked list, but the rest of the list is computed on demand. class Stream: A lazily computed linked list. class empty: pass empty = empty() The way in which names are looked up in Scheme and Python is called lexical scope (or static scope). Lexical scope: The parent of a frame is the environment in which a procedure was defined. (lambda ) Dynamic scope: The parent of a frame is the environment in which a procedure was called. (mu ) > (define f (mu (x) (+ x y))) > (define g (lambda (x y) (f (+ x x)))) > (g 7) reduce(, [,,, ], ) -> ,777,6 def init (self,, compute_rest=lambda: Stream.empty): self. = self._compute_rest = compute_rest def rest(self): Return the rest of the stream, computing it if necessary. if self._compute_rest is not None: self._rest = self._compute_rest() self._compute_rest = None return self._rest def integer_stream(=): def compute_rest(): return integer_stream(+) return Stream(, compute_rest) Stored explicitly [ Streams are lazily computed linked lists rest [ Evaluated lazily def filter_stream(fn, s): def map_stream(fn, s): if s is Stream.empty: if s is Stream.empty: return s return s def compute_rest(): def compute_rest(): return filter_stream(fn, s.rest) return map_stream(fn, s.rest) if fn(s.): return Stream(fn(s.), compute_rest) return Stream(s., compute_rest) return compute_rest() class LetterIter: def init (self, start=a, end=e): self.next_letter = start self.end = end def next (self): if self.next_letter >= self.end: raise StopIteration result = self.next_letter self.next_letter = chr(ord(result)+) return result class Letters: def init (self, start=a, end=e): self.start = start self.end = end def iter (self): return LetterIter(self.start, self.end) def letters_generator(next_letter, end): while next_letter < end: yield next_letter next_letter = chr(ord(next_letter)+) A generator is an iterator backed by a generator function. Each time a generator function is called, it returns a generator. A table has columns and rows Latitude Longitude Name Berkeley create table parents as select "abraham" as parent, "barack" as child union select "abraham", "clinton" union select "delano", "herbert" union select "fillmore", "abraham" union select "fillmore", "delano" union select "fillmore", "grover" union select "eisenhower", "fillmore"; >>> a_to_c = LetterIter(a, c) >>> next(a_to_c) a >>> next(a_to_c) b >>> next(a_to_c) Traceback (most recent call last): StopIteration >>> b_to_k = Letters(b, k) >>> _iterator = b_to_k. iter () >>> next(_iterator) b >>> next(_iterator) c >>> _iterator = iter(b_to_k) >>> _iterator. next () b >>> _iterator. next () d >>> for letter in letters_generator(a, e): print(letter) a b c d 7 Cambridge 5 9 Minneapolis A row has a value for each column select [] as [name], [] as [name], ; select [columns] from [table] where [condition] order by [order]; create table dogs as select "abraham" as name, "long" as fur union select "barack", "short" union select "clinton", "long" union select "delano", "long" union select "eisenhower", "short" union select "fillmore", "curly" union select "grover", "short" union select "herbert", "curly"; A column has a name and a type select a.child as, b.child as from parents as a, parents as b where a.parent = b.parent and a.child < b.child; E F A D G B C H First barack abraham abraham delano with ancestors(ancestor, descendent) as ( select parent, child from parents union select ancestor, child from ancestors, parents where parent = descendent ) select ancestor from ancestors where descendent="herbert"; create table pythagorean_triples as with i(n) as ( select union select n+ from i where n < ) select a.n as a, b.n as b, c.n as c from i as a, i as b, i as c where a.n < b.n and a.n*a.n + b.n*b.n = c.n*c.n; Second clinton delano grover grover ancestor delano fillmore eisenhower a b c The number of groups is the number of unique values of an A having clause filters the set of groups that are aggregated select weight/legs, count(*) from animals group by weight/legs having count(*)>; kind legs weight weight/ legs count(*) 5 weight/legs=5 weight/legs= weight/legs= weight/legs= weight/legs=5 weight/legs=6 dog cat ferret parrot 6 penguin t-rex

6 CS 6A Final Exam Study Guide Page Scheme programs consist of s, which can be: Primitive s:,., true, +, quotient, Combinations: (quotient ), (not true), Numbers are self-evaluating; symbols are bound to values. Call s have an operator and or more operands. A combination that is not a call is a special form: If : (if <predicate> <consequent> <alternative>) Binding names: (define <name> <>) New procedures: (define (<name> <formal parameters>) <body>) > (define pi.) > (* pi ) 6. Lambda s evaluate to anonymous procedures. (lambda (<formal-parameters>) <body>) Two equivalent s: (define (plus x) (+ x )) (define plus (lambda (x) (+ x ))) An operator can be a combination too: > (define (abs x) (if (< x ) (- x) x)) > (abs -) λ ((lambda (x y z) (+ x y (square z))) ) In the late 95s, computer scientists used confusing names. cons: Two-argument procedure that creates a pair car: Procedure that returns the element of a pair cdr: Procedure that returns the element of a pair nil: The empty list They also used a non-obvious notation for linked lists. A (linked) Scheme list is a pair in which the element is nil or a Scheme list. Scheme lists are written as space-separated combinations. A dotted list has an arbitrary value for the element of the last pair. Dotted lists may not be well-formed lists. > (define x (cons )) > x (. ) > (car x) > (cdr x) Not a well-formed list! > (cons (cons (cons (cons nil)))) ( ) Symbols normally refer to values; how do we refer to symbols? > (define a ) > (define b ) > (list a b) ( ) No sign of a and b in the resulting value Quotation is used to refer to symbols directly in Lisp. > (list a b) (a b) Symbols are now values > (list a b) (a ) Quotation can also be applied to combinations to form lists. > (car (a b c)) a > (cdr (a b c)) (b c) Dots can be used in a quoted list to specify the element of the final pair. > (cdr (cdr (. ))) However, dots appear in the output only of ill-formed lists. > (. ) (. ) > (. ( )) ( ) > (. nil) ( ) > (cdr (( ). (. (5)))) ( 5) nil nil class Pair: A Pair has and attributes. >>> s = Pair(, Pair(, Pair(, nil))) >>> print(s) ( ) >>> len(s) >>> print(pair(, )) (. ) >>> print(pair(, Pair(, ))) (. ) * For a Pair to be a well-formed list, is either a well-formed list or nil. def init (self,, ): self. = self. = + * nil 6 Calculator Expression (* (+ 5) (* 6 7 )) Expression Tree 5 nil The Calculator language has primitive s and call s * + 5 * 6 7 Representation as Pairs 7 nil A basic interpreter has two parts: a parser and an evaluator. lines Parser Evaluator value (+ ) Pair(+, Pair(, Pair(, nil))) (* (+ ) (- ) (* 5.6)) Lines forming a Scheme scheme_reader.py Pair(*, Pair(Pair(+, ))) printed as (* (+ (- ) (* 5.6)) ) A number or a Pair with an operator as its element scalc.py A Scheme list is written as elements in parentheses: (<element> <element> <elementn>) A number Each <element> can be a combination or atom (primitive). (+ (* (+ (* ) (+ 5))) (+ (- 7) 6)) A Scheme list The task of parsing a language involves coercing a string representation of an to the itself. Parsers must validate that s are well-formed. A Parser takes a sequence of lines and returns an. Lines (+ (- ) (* 5.6)) Lexical analysis (, +, Tokens (, -,, ) (, *,, 5.6, ), ) Iterative process Checks for malformed tokens Determines types of tokens Processes one line at a time Syntactic analysis Expression Pair(+, Pair(, )) printed as (+ (- ) (* 5.6)) Tree-recursive process Balances parentheses Returns tree structure Processes multiple lines Syntactic analysis identifies the hierarchical structure of an, which may be nested. Each call to scheme_read consumes the input tokens for exactly one. Base case: symbols and numbers Recursive call: scheme_read sub-s and combine them Base cases: Primitive values (numbers) Look up values bound to symbols Eval Recursive calls: Eval(operator, operands) of call s Apply(procedure, arguments) Eval(sub-s) of special forms Requires an environment for name lookup Base cases: Built-in primitive procedures The structure of the Scheme interpreter Apply Recursive calls: Eval(body) of user-defined procedures To apply a user-defined procedure, create a new frame in which formal parameters are bound to argument values, whose parent is the env of the procedure, then evaluate the body of the procedure in the environment that starts with this new frame. (define (f s) (if (null? s) () (cons (car s) (f (cdr s))))) (f (list )) g: Global frame [parent=g] [parent=g] [parent=g] f s s s LambdaProcedure instance [parent=g] Pair Pair A procedure call that has not yet returned is active. Some procedure calls are tail calls. A Scheme interpreter should support an unbounded number of active tail calls. A tail call is a call in a tail context, which are: The last body in lambda, define, begin, and, or s Expressions & (consequent & alternative) in a tail context if The non-predicate s of a cond (define (factorial n k) (if (= n ) k (factorial (- n ) nil (define (length s) (if (null? s) (+ (length (cdr s))))) (* k n)))) Not a tail call (define (length-tail s) (define (length-iter s n) Recursive call is a tail call (if (null? s) n (length-iter (cdr s) (+ n)) ) ) (length-iter s ) ) Creates a new environment each time a userdefined procedure is applied

Structure and Interpretation of Computer Programs Fall 2014 Midterm 2

Structure and Interpretation of Computer Programs Fall 2014 Midterm 2 CS 6A Structure and Interpretation of Computer Programs Fall 04 Midterm INSTRUCTIONS You have hours to complete the exam. The exam is closed book, closed notes, closed computer, closed calculator, except

More information

Structure and Interpretation of Computer Programs Fall 2012 Alternate Midterm 1

Structure and Interpretation of Computer Programs Fall 2012 Alternate Midterm 1 CS 6A Structure and Interpretation of Computer Programs Fall 0 Alternate Midterm INSTRUCTIONS You have hours to complete the exam. The exam is closed book, closed notes, closed computer, closed calculator,

More information

Measuring Efficiency

Measuring Efficiency Growth Announcements Measuring Efficiency Recursive Computation of the Fibonacci Sequence Our first example of tree recursion: fib(3) fib(5) fib(4) def fib(n): if n == 0: return 0 elif n == 1: return 1

More information

Structure and Interpretation of Computer Programs

Structure and Interpretation of Computer Programs CS 6A Spring 0 Structure and Interpretation of Computer Programs Final INSTRUCTIONS You have hours to complete the exam. The exam is closed book, closed notes, closed computer, closed calculator, except

More information

61A LECTURE 12 OOP 2, INHERITANCE. Steven Tang and Eric Tzeng July 14, 2013

61A LECTURE 12 OOP 2, INHERITANCE. Steven Tang and Eric Tzeng July 14, 2013 61A LECTURE 12 OOP 2, INHERITANCE Steven Tang and Eric Tzeng July 14, 2013 Announcements Midterm grades are up Average: 34 First quartile: 26.5 Median: 36.0 Third quartile: 43.0 Hog contest strategy due

More information

61A LECTURE 17 ORDERS OF GROWTH, EXCEPTIONS. Steven Tang and Eric Tzeng July 23, 2013

61A LECTURE 17 ORDERS OF GROWTH, EXCEPTIONS. Steven Tang and Eric Tzeng July 23, 2013 61A LECTURE 17 ORDERS OF GROWTH, EXCEPTIONS Steven Tang and Eric Tzeng July 23, 2013 Announcements Regrades for project 1 composition scores, due by next Monday See Piazza post for more details Midterm

More information

Object-Oriented Programming

Object-Oriented Programming 61A Lecture 15 Announcements Object-Oriented Programming Object-Oriented Programming A method for organizing programs Data abstraction Bundling together information and related behavior John's Account

More information

61A Lecture 32. Wednesday, November 14

61A Lecture 32. Wednesday, November 14 61A Lecture 32 Wednesday, November 14 Processing Sequential Data 2 Processing Sequential Data Many data sets can be viewed and processed sequentially: 2 Processing Sequential Data Many data sets can be

More information

Database Management Systems

Database Management Systems 61A Lecture 33 Announcements Database Management Systems Database Management System Architecture Architecture of a Database System by Hellerstein, Stonebreaker, and Hamilton 4 Query Planning The manner

More information

61A Lecture 4. Monday, September 9

61A Lecture 4. Monday, September 9 61A Lecture 4 Monday, September 9 Announcements Homework 1 due Tuesday 9/10 at 5pm; Late homework is not accepted! Quiz on Wednesday 9/11 released at 1pm, due Thursday 9/12 at 11:59pm Open-computer: You

More information

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

Summer 2017 Discussion 10: July 25, Introduction. 2 Primitives and Define CS 6A Scheme Summer 207 Discussion 0: July 25, 207 Introduction In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write Scheme programs,

More information

Structure and Interpretation of Computer Programs Fall 2012 Alternate Midterm 2

Structure and Interpretation of Computer Programs Fall 2012 Alternate Midterm 2 CS 6A Structure and Interpretation of Computer Programs Fall 202 Alternate Midterm 2 INSTRUCTIONS You have 2 hours to complete the exam. The exam is closed book, closed notes, closed computer, closed calculator,

More information

Structure and Interpretation of Computer Programs

Structure and Interpretation of Computer Programs CS 6A Fall 206 Structure and Interpretation of Computer Programs Final Solutions INSTRUCTIONS You have hours to complete the exam. The exam is closed book, closed notes, closed computer, closed calculator,

More information

TAIL RECURSION, SCOPE, AND PROJECT 4 11

TAIL RECURSION, SCOPE, AND PROJECT 4 11 TAIL RECURSION, SCOPE, AND PROJECT 4 11 COMPUTER SCIENCE 61A Noveber 12, 2012 1 Tail Recursion Today we will look at Tail Recursion and Tail Call Optimizations in Scheme, and how they relate to iteration

More information

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

SCHEME 8. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. March 23, 2017 SCHEME 8 COMPUTER SCIENCE 61A March 2, 2017 1 Introduction In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write Scheme programs,

More information

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

Fall 2018 Discussion 8: October 24, 2018 Solutions. 1 Introduction. 2 Primitives CS 6A Scheme Fall 208 Discussion 8: October 24, 208 Solutions Introduction In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write

More information

Structure and Interpretation of Computer Programs

Structure and Interpretation of Computer Programs CS 61A Fall 2016 Structure and Interpretation of Computer Programs Final INSTRUCTIONS You have 3 hours to complete the exam. The exam is closed book, closed notes, closed computer, closed calculator, except

More information

61A LECTURE 7 DATA ABSTRACTION. Steven Tang and Eric Tzeng July 3, 2013

61A LECTURE 7 DATA ABSTRACTION. Steven Tang and Eric Tzeng July 3, 2013 61A LECTURE 7 DATA ABSTRACTION Steven Tang and Eric Tzeng July 3, 2013 Announcements Trends project released later today. Due in ~2 weeks Extra midterm office hours Sunday, from noon to 6pm in 310 Soda

More information

Functional Programming. Pure Functional Programming

Functional Programming. Pure Functional Programming Functional Programming Pure Functional Programming Computation is largely performed by applying functions to values. The value of an expression depends only on the values of its sub-expressions (if any).

More information

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

Fall 2017 Discussion 7: October 25, 2017 Solutions. 1 Introduction. 2 Primitives CS 6A Scheme Fall 207 Discussion 7: October 25, 207 Solutions Introduction In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write

More information

An introduction to Scheme

An introduction to Scheme An introduction to Scheme Introduction A powerful programming language is more than just a means for instructing a computer to perform tasks. The language also serves as a framework within which we organize

More information

SCHEME 10 COMPUTER SCIENCE 61A. July 26, Warm Up: Conditional Expressions. 1. What does Scheme print? scm> (if (or #t (/ 1 0)) 1 (/ 1 0))

SCHEME 10 COMPUTER SCIENCE 61A. July 26, Warm Up: Conditional Expressions. 1. What does Scheme print? scm> (if (or #t (/ 1 0)) 1 (/ 1 0)) SCHEME 0 COMPUTER SCIENCE 6A July 26, 206 0. Warm Up: Conditional Expressions. What does Scheme print? scm> (if (or #t (/ 0 (/ 0 scm> (if (> 4 3 (+ 2 3 4 (+ 3 4 (* 3 2 scm> ((if (< 4 3 + - 4 00 scm> (if

More information

Structure and Interpretation of Computer Programs

Structure and Interpretation of Computer Programs CS 61A Fall 2013 Structure and Interpretation of Computer Programs Final Solutions INSTRUCTIONS You have 3 hours to complete the exam. The exam is closed book, closed notes, closed computer, closed calculator,

More information

MEMOIZATION, RECURSIVE DATA, AND SETS

MEMOIZATION, RECURSIVE DATA, AND SETS MEMOIZATION, RECURSIVE DATA, AND SETS 4b COMPUTER SCIENCE 61A July 18, 2013 1 Memoization Later in this class, you ll learn about orders of growth and how to analyze exactly how efficient (or inefficient)

More information

Spring 2018 Discussion 7: March 21, Introduction. 2 Primitives

Spring 2018 Discussion 7: March 21, Introduction. 2 Primitives CS 61A Scheme Spring 2018 Discussion 7: March 21, 2018 1 Introduction In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write Scheme

More information

Structure and Interpretation of Computer Programs Spring 2014 Final (with corrections)

Structure and Interpretation of Computer Programs Spring 2014 Final (with corrections) CS 61A Structure and Interpretation of Computer Programs Spring 2014 Final (with corrections) INSTRUCTIONS You have 3 hours to complete the exam. The exam is open book and open notes. You may not use a

More information

ENVIRONMENT DIAGRAMS AND RECURSION 2

ENVIRONMENT DIAGRAMS AND RECURSION 2 ENVIRONMENT DIAGRAMS AND RECURSION 2 COMPUTER SCIENCE 61A February 4, 2016 1 Environment Diagrams An environment diagram keeps track of all the variables that have been defined and the values they are

More information

STREAMS, ITERATORS, AND BINARY TREES 10

STREAMS, ITERATORS, AND BINARY TREES 10 STREAMS, ITERATORS, AND BINARY TREES 10 COMPUTER SCIENCE 61A April 10, 2017 1 Streams A stream is a lazily-evaluated linked list. A stream s elements (except for the first element) are only computed when

More information

Structure and Interpretation of Computer Programs

Structure and Interpretation of Computer Programs CS 6A Fall 05 Structure and Interpretation of Computer Programs Final INSTRUCTIONS You have hours to complete the exam. The exam is closed book, closed notes, closed computer, closed calculator, except

More information

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

SCHEME 7. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. October 29, 2015 SCHEME 7 COMPUTER SCIENCE 61A October 29, 2015 1 Introduction In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write Scheme programs,

More information

Declarative Programming

Declarative Programming Declarative Programming Announcements Declarative Languages Database Management Systems Database management systems (DBMS) are important, heavily used, and interesting! A table is a collection of records,

More information

Interpreters and Tail Calls Fall 2017 Discussion 8: November 1, 2017 Solutions. 1 Calculator. calc> (+ 2 2) 4

Interpreters and Tail Calls Fall 2017 Discussion 8: November 1, 2017 Solutions. 1 Calculator. calc> (+ 2 2) 4 CS 61A Interpreters and Tail Calls Fall 2017 Discussion 8: November 1, 2017 Solutions 1 Calculator We are beginning to dive into the realm of interpreting computer programs that is, writing programs that

More information

Chapter 1. Fundamentals of Higher Order Programming

Chapter 1. Fundamentals of Higher Order Programming Chapter 1 Fundamentals of Higher Order Programming 1 The Elements of Programming Any powerful language features: so does Scheme primitive data procedures combinations abstraction We will see that Scheme

More information

Organization of Programming Languages CS3200/5200N. Lecture 11

Organization of Programming Languages CS3200/5200N. Lecture 11 Organization of Programming Languages CS3200/5200N Razvan C. Bunescu School of Electrical Engineering and Computer Science bunescu@ohio.edu Functional vs. Imperative The design of the imperative languages

More information

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

Scheme Tutorial. Introduction. The Structure of Scheme Programs. Syntax Scheme Tutorial Introduction Scheme is an imperative language with a functional core. The functional core is based on the lambda calculus. In this chapter only the functional core and some simple I/O is

More information

Reminder: John the Patriotic Dog Breeder

Reminder: John the Patriotic Dog Breeder Tables Announcements Joining Tables Reminder: John the Patriotic Dog Breeder Parents: Parent Eisenhower Child CREATE TABLE parents AS SELECT "abraham" AS parent, "barack" AS child UNION SELECT "abraham",

More information

SEQUENCES AND TREES 4

SEQUENCES AND TREES 4 SEQUENCES AND TREES 4 COMPUTER SCIENCE 61A February 19, 2015 1 List Comprehension A list comprehension is a compact way to create a list whose elements are the results of applying a fixed expression to

More information

Delayed Expressions Fall 2017 Discussion 9: November 8, Iterables and Iterators. For Loops. Other Iterable Uses

Delayed Expressions Fall 2017 Discussion 9: November 8, Iterables and Iterators. For Loops. Other Iterable Uses CS 6A Delayed Expressions Fall 07 Discussion 9: November 8, 07 Iterables and Iterators An iterable is any container that can be processed sequentially. Examples include lists, tuples, strings, and dictionaries.

More information

61A LECTURE 15 MEMOIZATION, RECURSIVE DATA, SETS

61A LECTURE 15 MEMOIZATION, RECURSIVE DATA, SETS 61A LECTURE 15 MEMOIZATION, RECURSIVE DATA, SETS Steven Tang and Eric Tzeng July 18, 2013 Now in a wider screen format! Who am I? What am I doing here? First two weeks of class (Chapter 1): FUNCTIONS Computational

More information

INTERPRETERS 8. 1 Calculator COMPUTER SCIENCE 61A. November 3, 2016

INTERPRETERS 8. 1 Calculator COMPUTER SCIENCE 61A. November 3, 2016 INTERPRETERS 8 COMPUTER SCIENCE 61A November 3, 2016 1 Calculator We are beginning to dive into the realm of interpreting computer programs that is, writing programs that understand other programs. In

More information

CS 360 Programming Languages Interpreters

CS 360 Programming Languages Interpreters CS 360 Programming Languages Interpreters Implementing PLs Most of the course is learning fundamental concepts for using and understanding PLs. Syntax vs. semantics vs. idioms. Powerful constructs like

More information

Streams, Delayed Evaluation and a Normal Order Interpreter. CS 550 Programming Languages Jeremy Johnson

Streams, Delayed Evaluation and a Normal Order Interpreter. CS 550 Programming Languages Jeremy Johnson Streams, Delayed Evaluation and a Normal Order Interpreter CS 550 Programming Languages Jeremy Johnson 1 Theme This lecture discusses the stream model of computation and an efficient method of implementation

More information

61A LECTURE 25 DECLARATIVE PROGRAMMING

61A LECTURE 25 DECLARATIVE PROGRAMMING 61A LCTUR 25 DCLARATIV PROGRAMMING Midterm grades up Class did well as a whole! glookup s test2 Regrades: Talk to your TA in person. Steven Tang and ric Tzeng August 6, 2013 Announcements Proj4 has been

More information

Structure and Interpretation of Computer Programs

Structure and Interpretation of Computer Programs CS 6A Spring 203 Structure and Interpretation of Computer Programs Final Solutions INSTRUCTIONS You have 3 hours to complete the exam. The exam is closed book, closed notes, closed computer, closed calculator,

More information

Structure and Interpretation of Computer Programs

Structure and Interpretation of Computer Programs CS 61A Summer 2014 Structure and Interpretation of Computer Programs Final Solutions INSTRUCTIONS ˆ You have 3 hours to complete the exam. ˆ The exam is closed book, closed notes, and closed electronics,

More information

Working with Lists 4

Working with Lists 4 CS 61A Lecture 10 Announcements Lists ['Demo'] Working with Lists 4 Working with Lists >>> digits = [1, 8, 2, 8] 4 Working with Lists >>> digits = [1, 8, 2, 8] >>> digits = [2//2, 2+2+2+2, 2, 2*2*2] 4

More information

61A LECTURE 22 TAIL CALLS, ITERATORS. Steven Tang and Eric Tzeng July 30, 2013

61A LECTURE 22 TAIL CALLS, ITERATORS. Steven Tang and Eric Tzeng July 30, 2013 61A LECTURE 22 TAIL CALLS, ITERATORS Steven Tang and Eric Tzeng July 30, 2013 Announcements Homework 12 due Thursday, not Monday. Take the time to get started on the project instead! Almost done with Scheme

More information

Final Exam Solutions. Structure and Interpretation of Computer Programs. Fall 2011 /12 /16 /12 /18 /10 /12 /80 INSTRUCTIONS

Final Exam Solutions. Structure and Interpretation of Computer Programs. Fall 2011 /12 /16 /12 /18 /10 /12 /80 INSTRUCTIONS CS 61A Fall 2011 Structure and Interpretation of Computer Programs Final Exam Solutions INSTRUCTIONS You have 3 hours to complete the exam. The exam is closed book, closed notes, closed computer, closed

More information

6.184 Lecture 4. Interpretation. Tweaked by Ben Vandiver Compiled by Mike Phillips Original material by Eric Grimson

6.184 Lecture 4. Interpretation. Tweaked by Ben Vandiver Compiled by Mike Phillips Original material by Eric Grimson 6.184 Lecture 4 Interpretation Tweaked by Ben Vandiver Compiled by Mike Phillips Original material by Eric Grimson 1 Interpretation Parts of an interpreter Arithmetic calculator

More information

CS61A Lecture 21. Amir Kamil UC Berkeley March 11, 2013

CS61A Lecture 21. Amir Kamil UC Berkeley March 11, 2013 CS61A Lecture 21 Amir Kamil UC Berkeley March 11, 2013 Announcements HW7 due on Wednesday Ants project out Looking Up Names Name expressions look up names in the environment Dot expressions look

More information

Scheme in Scheme: The Metacircular Evaluator Eval and Apply

Scheme in Scheme: The Metacircular Evaluator Eval and Apply Scheme in Scheme: The Metacircular Evaluator Eval and Apply CS21b: Structure and Interpretation of Computer Programs Brandeis University Spring Term, 2015 The metacircular evaluator is A rendition of Scheme,

More information

SCHEME AND CALCULATOR 5b

SCHEME AND CALCULATOR 5b SCHEME AND CALCULATOR 5b COMPUTER SCIENCE 6A July 25, 203 In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write Scheme programs,

More information

Documentation for LISP in BASIC

Documentation for LISP in BASIC Documentation for LISP in BASIC The software and the documentation are both Copyright 2008 Arthur Nunes-Harwitt LISP in BASIC is a LISP interpreter for a Scheme-like dialect of LISP, which happens to have

More information

INTERPRETERS AND TAIL CALLS 9

INTERPRETERS AND TAIL CALLS 9 INTERPRETERS AND TAIL CALLS 9 COMPUTER SCIENCE 61A April 9, 2015 We are beginning to dive into the realm of interpreting computer programs that is, writing programs that understand other programs. In order

More information

Functional Programming

Functional Programming Functional Programming CS331 Chapter 14 Functional Programming Original functional language is LISP LISt Processing The list is the fundamental data structure Developed by John McCarthy in the 60 s Used

More information

61A Lecture 2. Friday, August 28, 2015

61A Lecture 2. Friday, August 28, 2015 61A Lecture 2 Friday, August 28, 2015 Names, Assignment, and User-Defined Functions (Demo) Types of Expressions Primitive expressions: 2 add 'hello' Number or Numeral Name String Call expressions: max

More information

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines.

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines. Chapter 1 Summary Comments are indicated by a hash sign # (also known as the pound or number sign). Text to the right of the hash sign is ignored. (But, hash loses its special meaning if it is part of

More information

Functional Programming. Pure Functional Languages

Functional Programming. Pure Functional Languages Functional Programming Pure functional PLs S-expressions cons, car, cdr Defining functions read-eval-print loop of Lisp interpreter Examples of recursive functions Shallow, deep Equality testing 1 Pure

More information

Scheme Basics > (butfirst '(help!)) ()

Scheme Basics > (butfirst '(help!)) () Scheme Basics > (butfirst '(help!)) () [The butfirst of a *sentence* containing one word is all but that word, i.e., the empty sentence. (BUTFIRST 'HELP!) without the inner parentheses would be butfirst

More information

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression Chapter 1 Summary Comments are indicated by a hash sign # (also known as the pound or number sign). Text to the right of the hash sign is ignored. (But, hash loses its special meaning if it is part of

More information

RLISTS AND THE ENVIRONMENT MODEL 9

RLISTS AND THE ENVIRONMENT MODEL 9 RLISTS AND THE ENVIRONMENT MODEL 9 COMPUTER SCIENCE 61A July 17, 2012 1 Recursive Lists (RLists) Earlier in the course, we worked with the Immutable Recursive List (IRList), which is an abstract data type

More information

ITERATORS AND STREAMS 9

ITERATORS AND STREAMS 9 ITERATORS AND STREAMS 9 COMPUTER SCIENCE 61A November 12, 2015 1 Iterators An iterator is an object that tracks the position in a sequence of values. It can return an element at a time, and it is only

More information

61A Lecture 2. Wednesday, September 4, 2013

61A Lecture 2. Wednesday, September 4, 2013 61A Lecture 2 Wednesday, September 4, 2013 Names, Assignment, and User-Defined Functions (Demo) Types of Expressions Primitive expressions: 2 add 'hello' Number or Numeral Name String Call expressions:

More information

Functional Programming. Pure Functional Languages

Functional Programming. Pure Functional Languages Functional Programming Pure functional PLs S-expressions cons, car, cdr Defining functions read-eval-print loop of Lisp interpreter Examples of recursive functions Shallow, deep Equality testing 1 Pure

More information

Notes on Higher Order Programming in Scheme. by Alexander Stepanov

Notes on Higher Order Programming in Scheme. by Alexander Stepanov by Alexander Stepanov August 1986 INTRODUCTION Why Scheme? Because it allows us to deal with: 1. Data Abstraction - it allows us to implement ADT (abstact data types) in a very special way. The issue of

More information

Functional Programming Languages (FPL)

Functional Programming Languages (FPL) Functional Programming Languages (FPL) 1. Definitions... 2 2. Applications... 2 3. Examples... 3 4. FPL Characteristics:... 3 5. Lambda calculus (LC)... 4 6. Functions in FPLs... 7 7. Modern functional

More information

61A LECTURE 18 SCHEME. Steven Tang and Eric Tzeng July 24, 2013

61A LECTURE 18 SCHEME. Steven Tang and Eric Tzeng July 24, 2013 61A LECTURE 18 SCHEME Steven Tang and Eric Tzeng July 24, 2013 What s happening today? We re learning a new language! After you know one language (Python), learning your second (Scheme) is much faster

More information

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

CS 61A Interpreters, Tail Calls, Macros, Streams, Iterators. Spring 2019 Guerrilla Section 5: April 20, Interpreters. CS 61A Spring 2019 Guerrilla Section 5: April 20, 2019 1 Interpreters 1.1 Determine the number of calls to scheme eval and the number of calls to scheme apply for the following expressions. > (+ 1 2) 3

More information

Why do we need an interpreter? SICP Interpretation part 1. Role of each part of the interpreter. 1. Arithmetic calculator.

Why do we need an interpreter? SICP Interpretation part 1. Role of each part of the interpreter. 1. Arithmetic calculator. .00 SICP Interpretation part Parts of an interpreter Arithmetic calculator Names Conditionals and if Store procedures in the environment Environment as explicit parameter Defining new procedures Why do

More information

Exceptions & a Taste of Declarative Programming in SQL

Exceptions & a Taste of Declarative Programming in SQL Exceptions & a Taste of Declarative Programming in SQL David E. Culler CS8 Computational Structures in Data Science http://inst.eecs.berkeley.edu/~cs88 Lecture 12 April 18, 2016 Computational Concepts

More information

Pairs and Lists. (cons 1 2) 1 2. (cons 2 nil) 2 nil. Not a well-formed list! 1 > (cdr x) 2 > (cons 1 (cons 2 (cons 3 (cons 4 nil)))) ( ) (Demo)

Pairs and Lists. (cons 1 2) 1 2. (cons 2 nil) 2 nil. Not a well-formed list! 1 > (cdr x) 2 > (cons 1 (cons 2 (cons 3 (cons 4 nil)))) ( ) (Demo) 61A Lecture 25 Announcements Pairs Review Pairs and Lists In the late 1950s, computer scientists used confusing names cons: Two-argument procedure that creates a pair car: Procedure that returns the first

More information

Chapter 2: Building Abstractions with Objects

Chapter 2: Building Abstractions with Objects Chapter 2: Building Abstractions with Objects Contents 2.1 Introduction 1 2.1.1 The Object Metaphor........................................ 1 2.1.2 Native Data Types..........................................

More information

SCHEME The Scheme Interpreter. 2 Primitives COMPUTER SCIENCE 61A. October 29th, 2012

SCHEME The Scheme Interpreter. 2 Primitives COMPUTER SCIENCE 61A. October 29th, 2012 SCHEME COMPUTER SCIENCE 6A October 29th, 202 In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write Scheme programs, we will eventually

More information

Structure and Interpretation of Computer Programs

Structure and Interpretation of Computer Programs CS 6A Summer 07 Structure and Interpretation of Computer Programs Final You have hours and 50 minutes to complete this exam. This exam is closed book, closed notes, closed computer, closed calculator,

More information

functional programming in Python, part 2

functional programming in Python, part 2 Programming Languages Week 2 functional programming in Python, part 2 College of Information Science and Engineering Ritsumeikan University review of part 1 eliminating assignment makes programs easier

More information

Streams and Evalutation Strategies

Streams and Evalutation Strategies Data and Program Structure Streams and Evalutation Strategies Lecture V Ahmed Rezine Linköpings Universitet TDDA69, VT 2014 Lecture 2: Class descriptions - message passing ( define ( make-account balance

More information

Structure and Interpretation of Computer Programs

Structure and Interpretation of Computer Programs CS 61A Fall 016 Structure and Interpretation of Computer Programs Midterm Solutions INSTRUCTIONS You have hours to complete the exam. The exam is closed book, closed notes, closed computer, closed calculator,

More information

20 Some terminology regarding trees: Parent node: A node that has branches. Parent nodes can have multiple branches.

20 Some terminology regarding trees: Parent node: A node that has branches. Parent nodes can have multiple branches. CS 61A Trees and Orders of Growth Summer 018 Discussion 5: July 05, 018 1 Trees In computer science, trees are recursive data structures that are widely used in various settings The diagram to the right

More information

6.037 Lecture 4. Interpretation. What is an interpreter? Why do we need an interpreter? Stages of an interpreter. Role of each part of the interpreter

6.037 Lecture 4. Interpretation. What is an interpreter? Why do we need an interpreter? Stages of an interpreter. Role of each part of the interpreter 6.037 Lecture 4 Interpretation Interpretation Parts of an interpreter Meta-circular Evaluator (Scheme-in-scheme!) A slight variation: dynamic scoping Original material by Eric Grimson Tweaked by Zev Benjamin,

More information

Structure and Interpretation of Computer Programs

Structure and Interpretation of Computer Programs CS 61A Spring 2015 Structure and Interpretation of Computer Programs Final Exam INSTRUCTIONS You have 3 hours to complete the exam. The exam is closed book, closed notes, closed computer, closed calculator,

More information

61A LECTURE 16 TREES, ORDERS OF GROWTH. Steven Tang and Eric Tzeng July 22, 2013

61A LECTURE 16 TREES, ORDERS OF GROWTH. Steven Tang and Eric Tzeng July 22, 2013 61A LECTURE 16 TREES, ORDERS OF GROWTH Steven Tang and Eric Tzeng July 22, 2013 Announcements Project 3 pushed back one day to August 2 Regrades for project 1 composition scores, due by next Monday Potluck

More information

Functional programming with Common Lisp

Functional programming with Common Lisp Functional programming with Common Lisp Dr. C. Constantinides Department of Computer Science and Software Engineering Concordia University Montreal, Canada August 11, 2016 1 / 81 Expressions and functions

More information

CS61A Lecture 15. Amir Kamil UC Berkeley February 25, 2013

CS61A Lecture 15. Amir Kamil UC Berkeley February 25, 2013 CS61A Lecture 15 Amir Kamil UC Berkeley February 25, 2013 Announcements HW5 due on Wednesday Trends project out Partners are required; find one in lab or on Piazza Will not work in IDLE New bug submission

More information

FP Foundations, Scheme

FP Foundations, Scheme FP Foundations, Scheme In Text: Chapter 15 1 Functional Programming -- Prelude We have been discussing imperative languages C/C++, Java, Fortran, Pascal etc. are imperative languages Imperative languages

More information

The Typed Racket Guide

The Typed Racket Guide The Typed Racket Guide Version 5.3.6 Sam Tobin-Hochstadt and Vincent St-Amour August 9, 2013 Typed Racket is a family of languages, each of which enforce

More information

Hog Contest Rules. Your name could be here FOREVER!

Hog Contest Rules. Your name could be here FOREVER! 61A Lecture 7 Announcements Hog Contest Rules Up to two people submit one entry; Max of one entry per person Your score is the number of entries against which you win more than 50.00001% of the time All

More information

Introduction to Functional Programming

Introduction to Functional Programming Introduction to Functional Programming Xiao Jia xjia@cs.sjtu.edu.cn Summer 2013 Scheme Appeared in 1975 Designed by Guy L. Steele Gerald Jay Sussman Influenced by Lisp, ALGOL Influenced Common Lisp, Haskell,

More information

CONTROL AND HIGHER ORDER FUNCTIONS 1

CONTROL AND HIGHER ORDER FUNCTIONS 1 CONTROL AND HIGHER ORDER FUNCTIONS 1 COMPUTER SCIENCE 61A January 29, 2015 1 Control Control structures direct the flow of logic in a program. For example, conditionals allow a program to skip sections

More information

A LISP Interpreter in ML

A LISP Interpreter in ML UNIVERSITY OF OSLO Department of Informatics A LISP Interpreter in ML Mandatory Assignment 1 INF3110 September 21, 2009 Contents 1 1 Introduction The purpose of this assignment is to write an interpreter,

More information

Object Oriented Programming

Object Oriented Programming Object Oriented Programming David E. Culler CS8 Computational Structures in Data Science http://inst.eecs.berkeley.edu/~cs88 Lecture 8 March 28, 2016 Computational Concepts Toolbox Data type: values, literals,

More information

1.3. Conditional expressions To express case distinctions like

1.3. Conditional expressions To express case distinctions like Introduction Much of the theory developed in the underlying course Logic II can be implemented in a proof assistant. In the present setting this is interesting, since we can then machine extract from a

More information

Fall Semester, The Metacircular Evaluator. Today we shift perspective from that of a user of computer langugaes to that of a designer of

Fall Semester, The Metacircular Evaluator. Today we shift perspective from that of a user of computer langugaes to that of a designer of 1 MASSACHVSETTS INSTITVTE OF TECHNOLOGY Department of Electrical Engineering and Computer Science 6.001 Structure and Interpretation of Computer Programs Fall Semester, 1996 Lecture Notes { October 31,

More information

Introduction to Scheme

Introduction to Scheme How do you describe them Introduction to Scheme Gul Agha CS 421 Fall 2006 A language is described by specifying its syntax and semantics Syntax: The rules for writing programs. We will use Context Free

More information

INTERPRETATION AND SCHEME LISTS 12

INTERPRETATION AND SCHEME LISTS 12 INTERPRETATION AND SCHEME LISTS 12 COMPUTER SCIENCE 61A July 26, 2012 1 Calculator Language We are beginning to dive into the realm of interpreting computer programs. To do so, we will examine a few new

More information

Functional Programming. Big Picture. Design of Programming Languages

Functional Programming. Big Picture. Design of Programming Languages Functional Programming Big Picture What we ve learned so far: Imperative Programming Languages Variables, binding, scoping, reference environment, etc What s next: Functional Programming Languages Semantics

More information

Functional Languages. Hwansoo Han

Functional Languages. Hwansoo Han Functional Languages Hwansoo Han Historical Origins Imperative and functional models Alan Turing, Alonzo Church, Stephen Kleene, Emil Post, etc. ~1930s Different formalizations of the notion of an algorithm

More information

Streams. CS21b: Structure and Interpretation of Computer Programs Spring Term, 2004

Streams. CS21b: Structure and Interpretation of Computer Programs Spring Term, 2004 Streams CS21b: Structure and Interpretation of Computer Programs Spring Term, 2004 We ve already seen how evaluation order can change behavior when we program with state. Now we want to investigate how

More information

Modern Programming Languages. Lecture LISP Programming Language An Introduction

Modern Programming Languages. Lecture LISP Programming Language An Introduction Modern Programming Languages Lecture 18-21 LISP Programming Language An Introduction 72 Functional Programming Paradigm and LISP Functional programming is a style of programming that emphasizes the evaluation

More information

Structure and Interpretation of Computer Programs

Structure and Interpretation of Computer Programs CS 6A Summer 5 Structure and Interpretation of Computer Programs Midterm Solutions INSTRUCTIONS You have hours to complete the exam. The exam is closed book, closed notes, closed computer, closed calculator,

More information

LINKED LISTS AND MIDTERM REVIEW

LINKED LISTS AND MIDTERM REVIEW LINKED LISTS AND MIDTERM REVIEW COMPUTER SCIENCE MENTORS 61A March 12 to March 14, 2018 For each of the following problems, assume linked lists are defined as follows: class Link: empty = () def init (self,

More information