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

Save this PDF as:

Size: px
Start display at page:

Download "Intro. Scheme Basics. scm> 5 5. scm>"

Transcription

1 Intro Let s take some time to talk about LISP. It stands for LISt Processing a way of coding using only lists! It sounds pretty radical, and it is. There are lots of cool things to know about LISP; if you re interested you can look up the benefits of functional programming. That s not part of the class, so we won t go over it in this note. We will start out by learning the building blocks of scheme, then we will talk about lists in Scheme, and finally we will try some practice problems. There will also be a list of every Scheme keyword, with examples, at the end of this note. Scheme Basics Scheme is one of a few dialects of LISP. If you read the intro, it should then be no surprise that Scheme is all about lists. In fact, everything in Scheme is either a primitive or a list! Let s explore the primitives first, and then we will talk more about lists. Don t worry about the if and lambda syntax in the examples below, we will talk about those later. scm> 5 5 scm> scm> scm> (if nil scm> (if scm> + #[+] scm> fred (lambda (x x Numbers are the primitive that we ll be dealing with the most. Unlike in Python, there is no difference between float (decimal and integer (whole number values. When a number is evaluated in Scheme, we get the value of the number, as you might expect. Booleans are another primitive in Scheme. There are two of them: and. These are just like True and False in Python. Recall that in Python we could also use numbers and strings instead of booleans. Scheme is also like that, but everything actually evaluates to, except for itself. Even 0 and nil are true values in Scheme. Symbols are the last kind of Scheme primitive. They look a bit like strings, but it s better to think of them like names. Symbols are the names bound to variables, functions, etc. For example, when we evaluate the symbol +, Scheme responds by writing #[+]. This is it s way of saying the name + is bound to the addition function. If we define a function called fred that just returns its input, then evaluating the name fred would give us the output in the example to the left. This is Scheme s way of saying fred is bound to that lambda function. Make sure you have a solid understanding of these different Scheme primitives before moving on to the next page.

2 As it turns out, everything else in Scheme is a list. Take this one for example: scm> ( It may not be totally obvious, but this really is a list. It s important to understand why, if you want to get to know how Scheme works. Let s break it down into individual elements: 1. The first element in the list is the symbol The second element in the list is the number The third element in the list is the number 2. So, if this is a list, then how come it returns a number? Well, when Scheme reads a list, it always assumes that the first element is a symbol bound to some function. It also assumes the other elements in the list are arguments for that function. So when it reads (+ 1 2, Scheme looks up the name +. It finds the addition function, and then adds the numbers 1 and 2. This produces the final output 3. What if we just want a list of numbers, like (1 2? Let s try it in the interpreter: scm> (1 2 Error: cannot call: 1 Remember, Scheme assumes the first element in the list is a symbol bound to a function. When it reads (1 2, it looks for a function bound to the name 1, but it can t find any because 1 is a number. That s why we get the error message. It s trying to call 1 like a function, but it can t. Okay then, is it possible for us to have Scheme output the list (1 2? Yes, we just need a function that can return the list (1 2. This is where cons and list come in. Understanding Scheme Lists In order to make Scheme lists, we need to know how they work. In fact, they are implemented just like linked lists. Here are a few examples: (1. (2. ( ((1. (. ( Notice that each dot represents the middle of a link. 1

3 You might have noticed that the Scheme lists written on the previous page were a little different from what the interpreter might produce. For reference, here s the first example from before: 1 2 Our answer: (1. (2. ( Scheme s answer: (1 2 Why doesn t our answer match the interpreter? Well, it turns out that both are correct. The reason Scheme writes (1 2 is because that version is a lot shorter and easier to read. However, the answer that we came up with is what it would look like, if written out completely. When you re writing Scheme and you are confused about what a list should look like, I recommend writing out the long version first. Students tend to make fewer mistakes that way. Then, you can convert to Scheme s shorter version by cancelling each dot with the pair of parentheses immediately after it. This cancellation process is drawn below, for both examples from the previous page: (1. (2. ( > (1 2. ( > (1 2 ((1. (. (2. 3 > ((1. (2. 3 > (( Notice there is still a dot in the second expression. That s because there is no pair of parentheses immediately after, so we can t cancel it with anything. Make sure you understand everything up to this point, before continuing. So, how do cons and list fit into all of this? They are just built-in functions that return lists. But they re very important and they work a little differently from one another, so let s go over them in some detail. Continue on the next page.

4 cons always takes exactly two arguments. In terms of Scheme lists, you can think of cons like this*: (cons a b > (a. b Or in terms of box-and-pointer diagrams, cons returns a single link where the first argument is in the first box, and the second argument is in the second box. Make sure you understand the 1 examples below: scm> (cons 1 2 ( scm> (cons 1 (cons 2 3 ( long version is (1. ( scm> (cons (cons 1 2 (cons 3 (cons 4 nil (( long version is ((1. 2. (3. (4. ( list supports any number of arguments. In terms of Scheme lists, you can think of list like this*: (list a b c > (a b c Or in terms of box-and-pointer diagrams, list returns a sequence of links where each argument is the first element in one of the links. Make sure you understand the examples below: scm> (list ( scm> (list 1 (list (1 ( * Don t worry about the quotes in this expression for now, we ll talk about those later.

5 This last example is a bit tricky. It is much easier if you analyze just one element at a time. Start with (1 2. The first element of our linked list is a pointer to that. Next work out the second element: (3 (4 ( 5. This one on its own can be hard, so do the same thing break it into one element at a time: 3, then the list resulting from (4 (, and finally 5. Keep going until you have the whole thing: scm> (list (list 1 2 (list 3 (list 4 nil ((1 2 (3 (4 ( To sum up: * cons takes 2 things, and puts them both in the same link. * list takes any number of things, and puts them in sequential links. Tip: If you want extra practice converting between Scheme lists and box-and-pointer diagrams, go to scheme.cs61a.org. Type in the command (demo autopair. Now try constructing a few lists using the cons and list commands; you should notice a corresponding box-andpointer diagram gets drawn to the screen. Try predicting some complicated ones, and check your correctness in the interpreter. If you get something wrong, take the time to figure out why you thought it was something else. That way, you don t make the same mistake again. Caution: Sometimes students think list is necessary because they don t want any dots in their answer. This is the case when we re cons-ing two numbers, but remember that applying cons on a number and a list will let us cancel the dot with the parentheses. Meanwhile, applying list on a number and a list would return a nested list. Always take the time to analyze which one you need, based on your arguments. Write out the long version of the Scheme list if you have to. It definitely matters that you pick the right function for the right situation. Before going on, make sure you understand everything so far.

6 Scheme in a Spreadsheet Even though Scheme is not as big a language as Python, it still has a lot of built-in keywords. These are nothing more than functions the developers of Scheme decided they would implement for you, to save you some time. You will be expected to know the functions that follow, and you should know how to use them. Make note of the subtleties, like the difference between pair? and list?, or between cons and list. If you find yourself wishing for more examples, just go to scheme.cs61a.org and play around with the interpreter. There, you will be able to answer any questions you have about Scheme, simply by writing out some examples and analyzing the results. With that said, here is Scheme in a spreadsheet. Don t let it intimidate you; work through each function one by one and make sure you get how they all work. Description if takes 3 arguments. If the first one is, then it returns the second one. Otherwise it returns the third one. Remember all values in Scheme are, except for the boolean itself. cond is like an if-elif-else chain. It can take any number of arguments. Each argument has to be a list of 2 elements, where the first element is the condition and the second element is the action to be taken on that condition. Note that only one action can be executed from a cond. The keyword else is a condition that always evaluates to ; it should be the last condition if you want to use it. Syntax (if condition do-if-true do-if-false scm> (if scm> (if scm> (if scm> (if nil nil nil ( (cond (case1 action1 (case2 action2 (case3 action3 scm> (cond ( nil... ((= (else 1 1 scm> (cond... ((null? ( ((null? ( ((null? ( 7 42

7 and in Scheme works just like it does in Python. It returns the first argument, or if all arguments are, it returns the last one. Remember, all values in Scheme are (including 0 and nil except for the boolean itself. or in Scheme works just like it does in Python. It returns the first argument, or if all arguments are, it returns the last one. not simply returns if its argument is, or if its argument is. define takes 2 arguments. The first one is a list where the first element is the name of the function and all other elements are the function s parameters. The second argument is what that function should evaluate to, in terms of its parameters. If the first element is not a list, then you will define a variable instead of a function. lambda is just like define, except the first argument doesn t contain a function name. That is the first argument in the lambda is just a list of parameters, and the second argument in the lambda is what to return in terms of those parameters. (and bool1 bool2 bool3 scm> (and 0 nil 5 5 scm> (and a (or bool1 bool2 bool3 scm> (or nil (/ 1 0 ( scm> (or (/ 1 0 a error (not bool1 scm> (not (and (+ 5 7 nil scm> (not (define (f p1 p2 p3 do-something scm> (define a 10 a scm> a 10 scm> (define (b 10 b scm> b (lambda ( 10 scm> (b 10 (lambda (p1 p2 p3 do-something scm> ((lambda (x (+ x scm> (define a (lambda (x... (cons x nil a scm> (a 5 (5

8 let can be confusing, so make sure you practice it! It takes two arguments: * The first argument in the let is a list, where each element is a pair containing a variable name and a value for that variable. * The second argument in the let is just some expression, in terms of the variables you defined. Note that the variables computed in the second argument cannot rely on each other! See the example at right, where b is defined in terms of the global value of a instead of the local value of a. car takes a list as its argument. It returns the first element of that list. cdr takes a list as its argument. It returns the second element of that list. Since Scheme lists are linked lists, keep in mind this second element will also be a list, if the argument is well-formed. cons takes 2 arguments, and puts them both in the same link. See the previous section of this note for more details and examples. list takes any number of arguments, and puts them in sequential links. See the previous section of this note for more details and examples. length takes in a list and returns the length of that list. (let ((var1 value1 (var2 value2 (var3 value3 body scm> (define a 5 a scm> (let ((a (b (+ a 1... (- a b 44 scm> (let ((x (lambda (y y... (y (lambda (x x... (+ (x 5 (y (car lst scm> (car (list (cons nil (3 (1. 2 (cdr lst scm> (cdr (list (cons nil (3 (( (3 (cons elem1 elem2 scm> (cons 1 2 (1. 2 (list el1 el2 el3 scm> (list 1 2 (1 2 scm> (list ( (length lst scm> (length nil 0 scm> (length ( scm> (length ( error

9 append takes any number of arguments. It returns all its arguments joined into one list, and it errors if the resulting list is not a valid Scheme list. boolean? returns if its argument is a boolean, otherwise it returns. integer? returns if its argument is a whole number, otherwise it returns. equal? returns if its 2 arguments evaluate to the same thing, otherwise it returns. = is the same as equal? except its arguments have to be numbers. Otherwise it errors. (append el1 el2 el3 scm> (append (list (cons 4 5 ( scm> (append (list (cons 4 nil... 5 ( scm> (append (list (cons error scm> (append (list (cons (1 error (boolean? arg scm> (boolean? 5 scm> (boolean? (integer? arg scm> (integer? a scm> (integer? (cons 1 nil scm> (integer? 3.14 (equal? arg1 arg2 scm> (equal? (list (cons 1 (list 2 3 scm> (equal? 5 (+ 4 1 scm> (equal? + + (= num1 num2 scm> (= (list (cons 1 (list 2 3 scm> (= 5 (+ 4 1

10 even? returns if its argument is an even number, otherwise it returns. odd? returns if its argument is an even number, otherwise it returns. null? returns if its argument is nil, a.k.a. (, otherwise it returns. list? returns if its argument is a wellformed list (i.e., no dots, otherwise it returns. pair? is like list? except it allows malformed lists too (i.e., dots are fine. quote simply tells Scheme not to evaluate its argument, so it returns the unevaluated argument without the quote. Notably, Scheme will try to make the argument a wellformed list if possible. It will also error if there is more than one element after any dot in the expression, since that s not a valid Scheme list. (even? num scm> (even? 0 (odd? num scm> (odd? nil error scm> (odd? 0 (null? arg scm> (null? ( scm> (null? nil (list? arg scm> (list? (cons 1 nil scm> (list? (cons 1 1 (pair? arg scm> (pair? (cons 1 nil scm> (pair? (cons 1 1 (quote arg OR arg scm> (quote a a scm> (quote (cons hi oops (cons hi oops scm> (1. (2. (five hello (1 2 five hello scm> (1. (... 5 error scm> (1. (2. ( five error

11 eval returns what Scheme would return, if Scheme were to evaluate the argument. (eval arg scm> (eval (list 1 2 (1 2 scm> (eval (even? 5 (even? 5 scm> (eval (eval (even? 5 scm> ((eval Building Scheme Lists Recursively A lot of the Scheme problems you see probably most of them will ask you to return a list. That sounds like a handy thing to know how to do, so let s practice. In general, we want to stick to this procedure: 1. Pick a base case. Since we re building a list, the condition should be whatever assures us that we should return the empty list, nil. Most of the time (null? lst is a good guess, where lst is some list we got as a parameter, but that s not always the case. 2. Now we build our list recursively. If one of our arguments is a list, then each recursive call should only take any action with respect to one element in that list the first one. We will take care of all the other elements when we recurse on the rest of the list. Note that there are many ways to take action with respect to the first element in the list. We could want to add it to a list of our own, or we might want to apply some function on it first. We might even use it to change the rest of the list before recursing. The point is, when we re in a recursive call, we pretend the first element is the only value we care about. Practice: repeat This one is from last semester s discussion worksheet. Define a function repeat that takes in parameters x and n. It should return a list of the number n, repeated x times. For example: scm> (repeat 3 5 (5 5 5 The first step is to determine a base case. Following the procedure above, let s think about what parameters would make us return nil. This is the same as asking what parameters would make us return a list of length 0. That happens when we repeat n a total of 0 times, so our base case is (= x 0. We have the following:

12 (define (repeat x n (if (= x 0 nil... How about when x is not 0? Then we need a list containing n, and a recursive call to give us the number n, repeated x-1 more times. n is a number, and the recursive call will give us a list, so should we use cons or list? cons would give us something like (n. (recursive call, but the dot cancels with the parenthesis so we end up with a flat list. list, on the other hand, gives us (n (recursive call, so we end up with a nested list. We choose cons, since we desire a flat list. Here is the final scheme program, side by side with the Python equivalent. Check that you understand both: (define (repeat x n def repeat(x, n: (if (= x 0 if x == 0: nil return [] (cons n (repeat (- x 1 n return [n]+repeat(x-1,n Caution: Sometimes it can be helpful to write the Python version of a program, as we have done here. However, a lot of the time this can just be more confusing. It happens to have worked out well in this case, but don t rely on that being so. Practice: filter We have a function f that takes a single number as its argument, and it returns either or. We also have a list of numbers, called lst. How can we get only the elements of lst for which f returns? The first step is to determine a base case. We should ask ourselves, when do we want to return nil? The answer is when lst itself is nil, because filtering an empty list should give us an empty list. So that makes our base case (null? lst. Here s what we have so far:

13 (define (filter f lst (if (null? lst nil... Now, recall from the procedure above that we want to build our desired list one element at a time. That means that right now we re only concerned with the first element in lst. Either we want it, or we don t. Let s think about each case: * If we want it, then we should have a list where the first element is (car lst and the rest of the elements come from a recursive call on the rest of lst. * If we don t want it, that means we only want the recursive call. (car lst should not be at the beginning. But how do we know if we want (car lst? From the description of filter, we should only use it if (f (car lst is. A few of my students have suggested writing the following: (if (= (car lst... ; we want (car lst... ; we don t want (car lst This works, but notice that (f (car lst itself evaluates to a boolean, so we can directly use it as the condition in the if statement, like this: (define (filter f lst (if (null? lst nil (if (f (car lst... ; we want (car lst... ; we don t want (car lst This is a valid Scheme expression, but it might be cumbersome to read. Let s try converting to a cond statement. Look at the previous section if you need to review the correct syntax.

14 (define (filter f lst (cond ((null? lst nil ((f (car lst... ; we want (car lst (else... ; we don t want (car lst Check to see you agree this is the same as what we had before. Now all there s left to do is fill out each of the conditional actions. If we want (car lst, then we ll need to join a number to the list we get from our recursive call. As in the previous example, we will need to use cons in order to get a flat list. If you don t understand why, take a look back to Example 1. On the other hand, when we don t want to use (car lst, then we somehow have to get a list from only our recursive call. But the recursive call is a list, so that s not a problem. If you ever find yourself thinking, I want a cons but I don t know what to cons this with, chances are you don t need to cons. This is a common mistake when you re just learning Scheme remember, if you already have the list you want there s no need to join it with anything else. Putting that all together, we get this: (define (filter f lst (cond ((null? lst nil ((f (car lst (cons (car lst (filter f (cdr lst (else (filter f (cdr lst If this is a bit confusing, try writing out a few iterations on paper. You can also try drawing an example using the (demo autopair command on scheme.cs61a.org. Practice: no-repeats Once we have defined a function like filter, we can use it to do more complicated things. For example, imagine I have a list called lst, but there are a lot of repeated elements in it. lst might look like ( How do we get the same list, but with all the repeats eliminated? For this example I would be looking for the list ( We are allowed to use the filter function. Here s the signature: (define (no-repeats lst...

15 Step one is the base case. When should we return nil? Just like in the last example, we return nil if (null? lst, so we ll make that our base case. For reference, here s the function: (define (no-repeats lst (if (null? lst nil... Now let s think about how we plan to build our list of non-repeated elements. From the procedure we came up with earlier, we know that we should only care about the first element right now. That means the problem is no longer finding all the repeats in lst; rather we are now only trying to find all the repeats of (car lst in lst. The rest will be handled when we recurse on the rest of the elements. Take a moment to think about the content of this paragraph really, really understand why it works. This is important. Okay, so then how do we get rid of all the repeats of (car lst from lst? Recall that we have the filter function from before. Perhaps try doing this part on your own; keep reading once you ve given it a go. We re trying to filter out all the duplicates of (car lst from (cdr lst. So, how do make that call to filter? We will have to come up with the right arguments. filter takes two of them: a function, and a list on which to apply the function. We should be applying our function on (cdr lst, since we ve decided that s what we re filtering. That gives us the following code, where the filtering function will go on the blank line when we re done: (define (no-repeats lst (if (null? lst nil (cons (car lst (filter (cdr lst Check that this all makes sense so far.

16 We need to filter for duplicates of (car lst. That means our function has to return for things that don t equal (car lst, and for things that equal (car lst. We could achieve this relatively easily by nesting a define up at the top of no-repeats, but let s do it with a lambda instead to get some practice. It will take in one argument, a number, and it will output a boolean. The syntax looks like this: (lambda (x ; x is a number The rest is just converting from English to Scheme: to check that x does not equal (car lst, we simply write (not (= x (car lst. Make sure the final lambda expression makes sense to you: (lambda (x (not (= x (car lst Then we just have to plug it in: (define (no-repeats lst (if (null? lst nil (cons (car lst (filter (lambda (x (not (= x (car lst (cdr lst Let s walk through what this does. First, we check that our list has at least one element. This was our base case. Next we decide that the first element must not be a repeat, since it is the first one. That s why we include it in the list we re returning, using cons. Then the filter function will check that this first element never occurs again in (cdr lst. It mostly works, but something is missing. What is it? Remember how we only want to take action regarding one element at a time, when we re recursively building a list? There was an assumption there, which was that we d get to all the other elements recursively. Thus, a quick check on the correctness of your program is just to look for a recursive call. If there isn t one, the odds are you missed something. Where should we put that recursive call in no-repeats? It has to operate on all the elements that are after

17 the first element, so we should recursively call on the result from filter. It is equally good to call it on (cdr lst inside of filter. Here s our finished product, with the recursive call included: (define (no-repeats lst (if (null? lst nil (cons (car lst (no-repeats (filter (lambda (x (not (= x (car lst (cdr lst Always remember your recursive call when you re doing problems like this one. Now try writing out a few iterations of this function, to convince yourself that it works. Also go back and identify how we were able to arrive at the solution by following the procedure detailed at the beginning of this section. Happy scheming.

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,

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

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

Scheme: Data. CS F331 Programming Languages CSCE A331 Programming Language Concepts Lecture Slides Monday, April 3, Glenn G.

Scheme: Data CS F331 Programming Languages CSCE A331 Programming Language Concepts Lecture Slides Monday, April 3, 2017 Glenn G. Chappell Department of Computer Science University of Alaska Fairbanks ggchappell@alaska.edu

CS61A Discussion Notes: Week 11: The Metacircular Evaluator By Greg Krimer, with slight modifications by Phoebus Chen (using notes from Todd Segal)

CS61A Discussion Notes: Week 11: The Metacircular Evaluator By Greg Krimer, with slight modifications by Phoebus Chen (using notes from Todd Segal) What is the Metacircular Evaluator? It is the best part

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 SCHEME. 1 What Would Scheme Print? COMPUTER SCIENCE MENTORS 61A. October 30 to November 3, Solution: Solutions begin on the following page.

MORE SCHEME COMPUTER SCIENCE MENTORS 61A October 30 to November 3, 2017 1 What Would Scheme Print? Solutions begin on the following page. 1. What will Scheme output? Draw box-and-pointer diagrams to help

Warm-up and Memoization

CSE341 Spring 05 Due Wednesday, May 11 Assignment 4 Part I Warm-up and Memoization Warm-up As a warm-up, write the following Scheme functions: 1. Write the function foldl of the form (foldl func initial

Project 2: Scheme Interpreter

Project 2: Scheme Interpreter CSC 4101, Fall 2017 Due: 12 November 2017 For this project, you will implement a simple Scheme interpreter in C++ or Java. Your interpreter should be able to handle the same

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

Symbolic Programming Symbols: +, -, 1, 2 etc. Symbolic expressions: (+ 1 2), (+ (* 3 4) 2) Symbolic programs are programs that manipulate symbolic expressions. Symbolic manipulation: you do it all the

Decisions, Decisions. Testing, testing C H A P T E R 7

C H A P T E R 7 In the first few chapters, we saw some of the basic building blocks of a program. We can now make a program with input, processing, and output. We can even make our input and output a little

Boolean Expressions. Is Equal and Is Not Equal

3 MAKING CHOICES Now that we ve covered how to create constants and variables, you re ready to learn how to tell your computer to make choices. This chapter is about controlling the flow of a computer

Functional abstraction. What is abstraction? Eating apples. Readings: HtDP, sections Language level: Intermediate Student With Lambda

Functional abstraction Readings: HtDP, sections 19-24. Language level: Intermediate Student With Lambda different order used in lecture section 24 material introduced much earlier sections 22, 23 not covered

Functional abstraction

Functional abstraction Readings: HtDP, sections 19-24. Language level: Intermediate Student With Lambda different order used in lecture section 24 material introduced much earlier sections 22, 23 not covered

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

Scheme Textbook, Sections 13.1 13.3, 13.7 1 Functional Programming Based on mathematical functions Take argument, return value Only function call, no assignment Functions are first-class values E.g., functions

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

Excel Basics Rice Digital Media Commons Guide Written for Microsoft Excel 2010 Windows Edition by Eric Miller

Excel Basics Rice Digital Media Commons Guide Written for Microsoft Excel 2010 Windows Edition by Eric Miller Table of Contents Introduction!... 1 Part 1: Entering Data!... 2 1.a: Typing!... 2 1.b: Editing

These are notes for the third lecture; if statements and loops.

These are notes for the third lecture; if statements and loops. 1 Yeah, this is going to be the second slide in a lot of lectures. 2 - Dominant language for desktop application development - Most modern

CS61A Notes 02b Fake Plastic Trees. 2. (cons ((1 a) (2 o)) (3 g)) 3. (list ((1 a) (2 o)) (3 g)) 4. (append ((1 a) (2 o)) (3 g))

CS61A Notes 02b Fake Plastic Trees Box and Pointer Diagrams QUESTIONS: Evaluate the following, and draw a box-and-pointer diagram for each. (Hint: It may be easier to draw the box-and-pointer diagram first.)

Part II Composition of Functions

Part II Composition of Functions The big idea in this part of the book is deceptively simple. It s that we can take the value returned by one function and use it as an argument to another function. By

Racket Style Guide Fall 2017

CS17 Integrated Introduction to Computer Science Hughes Racket Style Guide Fall 2017 Contents 1 Introduction 1 2 Naming 1 3 Formatting 1 4 Equality 3 5 Conditionals 4 5.1 Prefer Cond to If......................................

How to Design Programs

How to Design Programs How to (in Racket): represent data variants trees and lists write functions that process the data See also http://www.htdp.org/ 1 Running Example: GUIs Pick a fruit: Apple Banana

COMPUTER SCIENCE IN THE NEWS. CS61A Lecture 21 Scheme TODAY REVIEW: DISPATCH DICTIONARIES DISPATCH DICTIONARIES 7/27/2012

COMPUTER SCIENCE IN THE NEWS CS6A Lecture 2 Scheme Jom Magrotker UC Berkeley EECS July 24, 202 http://spectrum.ieee.org/tech talk/robotics/artificial intelligence/a texas hold em tournament for ais 2 TODAY

(Provisional) Lecture 22: Rackette Overview, Binary Tree Analysis 10:00 AM, Oct 27, 2017

Integrated Introduction to Computer Science Hughes (Provisional) Lecture 22: Rackette Overview, Binary Tree Analysis 10:00 Contents 1 Announcements 1 2 An OCaml Debugging Tip 1 3 Introduction to Rackette

CS 220: Introduction to Parallel Computing. Arrays. Lecture 4

CS 220: Introduction to Parallel Computing Arrays Lecture 4 Note: Windows I updated the VM image on the website It now includes: Sublime text Gitkraken (a nice git GUI) And the git command line tools 1/30/18

Scheme as implemented by Racket

Scheme as implemented by Racket (Simple view:) Racket is a version of Scheme. (Full view:) Racket is a platform for implementing and using many languages, and Scheme is one of those that come out of the

If Statements, For Loops, Functions

Fundamentals of Programming If Statements, For Loops, Functions Table of Contents Hello World Types of Variables Integers and Floats String Boolean Relational Operators Lists Conditionals If and Else Statements

CS450: Structure of Higher Level Languages Spring 2018 Assignment 7 Due: Wednesday, April 18, 2018

CS450: Structure of Higher Level Languages Spring 2018 Assignment 7 Due: Wednesday, April 18, 2018 Taken from assignments by Profs. Carl Offner and Ethan Bolker Part 1 - Modifying The Metacircular Evaluator

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

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

Foundations, Reasoning About Algorithms, and Design By Contract CMPSC 122

Foundations, Reasoning About Algorithms, and Design By Contract CMPSC 122 I. Logic 101 In logic, a statement or proposition is a sentence that can either be true or false. A predicate is a sentence in

Beyond Blocks: Python Session #1

Beyond Blocks: Session #1 CS10 Spring 2013 Thursday, April 30, 2013 Michael Ball Beyond Blocks : : Session #1 by Michael Ball adapted from Glenn Sugden is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike

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,

Week 2: The Clojure Language. Background Basic structure A few of the most useful facilities. A modernized Lisp. An insider's opinion

Week 2: The Clojure Language Background Basic structure A few of the most useful facilities A modernized Lisp Review of Lisp's origins and development Why did Lisp need to be modernized? Relationship to

MetacircularScheme! (a variant of lisp)

MetacircularScheme! (a variant of lisp) Lisp = Beauty Passed on through ages Basic Expressions (function arg1 arg2 ) To evaluate an expression, apply the functionto the arguments. (+ 1 2)? => 3 (sqrt4)?

QUIZ. What is wrong with this code that uses default arguments?

QUIZ What is wrong with this code that uses default arguments? Solution The value of the default argument should be placed in either declaration or definition, not both! QUIZ What is wrong with this code

STREAMS 10. Basics of Streams. Practice with Streams COMPUTER SCIENCE 61AS. 1. What is a stream?

STREAMS 10 COMPUTER SCIENCE 61AS Basics of Streams 1. What is a stream? A stream is an element and a promise to evaluate the rest of the stream. Streams are a clever idea that allows one to use sequence

Scheme: Strings Scheme: I/O

Scheme: Strings Scheme: I/O CS F331 Programming Languages CSCE A331 Programming Language Concepts Lecture Slides Wednesday, April 5, 2017 Glenn G. Chappell Department of Computer Science University of

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.

Working with recursion

Working with recursion Readings: HtDP, sections 11, 12, 13 (Intermezzo 2). We can extend the idea of a self-referential definition to defining the natural numbers, which leads to the use of recursion in

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,

Programming with Math and Logic

.. Programming with Math and Logic an invitation to functional programming Ed Morehouse Wesleyan University The Plan why fp? terms types interfaces The What and Why of Functional Programming Computing

Project 1: Scheme Pretty-Printer

Project 1: Scheme Pretty-Printer CSC 4101, Fall 2017 Due: 7 October 2017 For this programming assignment, you will implement a pretty-printer for a subset of Scheme in either C++ or Java. The code should

Variables, expressions and statements

Variables, expressions and statements 2.1. Values and data types A value is one of the fundamental things like a letter or a number that a program manipulates. The values we have seen so far are 2 (the

Hello World! Computer Programming for Kids and Other Beginners. Chapter 1. by Warren Sande and Carter Sande. Copyright 2009 Manning Publications

Hello World! Computer Programming for Kids and Other Beginners by Warren Sande and Carter Sande Chapter 1 Copyright 2009 Manning Publications brief contents Preface xiii Acknowledgments xix About this

Shorthand for values: variables

Chapter 2 Shorthand for values: variables 2.1 Defining a variable You ve typed a lot of expressions into the computer involving pictures, but every time you need a different picture, you ve needed to find

mk-convert Contents 1 Converting to minikanren, quasimatically. 08 July 2014

mk-convert 08 July 2014 Contents 1 Converting to minikanren, quasimatically. 1 1.1 Variations on a Scheme..................... 2 1.2 Racket to minikanren, nally.................. 8 1.3 Back to the beginning......................

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

Racket Next 2+ weeks will use the Racket language (not ML) and the DrRacket programming environment (not emacs) Installation / basic usage instructions on course website CSE34: Programming Languages Lecture

What is Iteration? CMPT-101. Recursion. Understanding Recursion. The Function Header and Documentation. Recursively Adding Numbers

What is Iteration? CMPT-101 Week 6 Iteration, Iteration, Iteration, Iteration, Iteration, Iteration,... To iterate means to do the same thing again and again and again and again... There are two primary

Getting Started. Excerpted from Hello World! Computer Programming for Kids and Other Beginners

Getting Started Excerpted from Hello World! Computer Programming for Kids and Other Beginners EARLY ACCESS EDITION Warren D. Sande and Carter Sande MEAP Release: May 2008 Softbound print: November 2008

Trombone players produce different pitches partly by varying the length of a tube.

Trombone players produce different pitches partly by varying the length of a tube. 7 Variables A variable is a connection between a name and a value.* That sounds simple enough, but some complexities arise

Be careful when deciding whether to represent data as integers or floats, and be sure that you consider all possible behaviors in computation.

Table of Contents: 1. Integers and floats 2. for vs. while loops 3. Checking boolean conditions with if/else 4. Docstrings 5. Changing collections while iterating over them 6. Directly Accessing Instance

Problem Solving for Intro to Computer Science

Problem Solving for Intro to Computer Science The purpose of this document is to review some principles for problem solving that are relevant to Intro to Computer Science course. Introduction: A Sample

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

1 A couple of Functions 1 Let's take another example of a simple lisp function { one that does insertion sort. Let us assume that this sort function takes as input a list of numbers and sorts them in ascending

CS152: Programming Languages. Lecture 7 Lambda Calculus. Dan Grossman Spring 2011

CS152: Programming Languages Lecture 7 Lambda Calculus Dan Grossman Spring 2011 Where we are Done: Syntax, semantics, and equivalence For a language with little more than loops and global variables Now:

Structure and Interpretation of Computer Programs

CS 61A Summer 2015 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,

A Brief Introduction to Scheme (II)

A Brief Introduction to Scheme (II) Philip W. L. Fong pwlfong@cs.uregina.ca Department of Computer Science University of Regina Regina, Saskatchewan, Canada Lists Scheme II p.1/29 Lists Aggregate data

Animations involving numbers

136 Chapter 8 Animations involving numbers 8.1 Model and view The examples of Chapter 6 all compute the next picture in the animation from the previous picture. This turns out to be a rather restrictive

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

Overview Announcement Announcement Lisp Basics CMUCL to be available on sun.cs. You may use GNU Common List (GCL http://www.gnu.org/software/gcl/ which is available on most Linux platforms. There is also

Lecture Transcript While and Do While Statements in C++

Lecture Transcript While and Do While Statements in C++ Hello and welcome back. In this lecture we are going to look at the while and do...while iteration statements in C++. Here is a quick recap of some

VARIABLES. Aim Understanding how computer programs store values, and how they are accessed and used in computer programs.

Lesson 2 VARIABLES Aim Understanding how computer programs store values, and how they are accessed and used in computer programs. WHAT ARE VARIABLES? When you input data (i.e. information) into a computer

An Introduction to Python

An Introduction to Python Day 2 Renaud Dessalles dessalles@ucla.edu Python s Data Structures - Lists * Lists can store lots of information. * The data doesn t have to all be the same type! (unlike many

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,

Properties and Definitions

Section 0.1 Contents: Operations Defined Multiplication as an Abbreviation Visualizing Multiplication Commutative Properties Parentheses Associative Properties Identities Zero Product Answers to Exercises

6.001 Notes: Section 5.1

6.001 Notes: Section 5.1 Slide 5.1.1 In this lecture we are going to continue with the theme of building abstractions. Thus far, we have focused entirely on procedural abstractions: the idea of capturing

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

Principles of Programming Languages Topic: Functional Programming Professor L. Thorne McCarty Spring 2003 CS 314, LS, LTM: Functional Programming 1 Scheme A program is an expression to be evaluated (in

Fundamentals. Fundamentals. Fundamentals. We build up instructions from three types of materials

Fundamentals We build up instructions from three types of materials Constants Expressions Fundamentals Constants are just that, they are values that don t change as our macros are executing Fundamentals

Your . A setup guide. Last updated March 7, Kingsford Avenue, Glasgow G44 3EU

fuzzylime WE KNOW DESIGN WEB DESIGN AND CONTENT MANAGEMENT 19 Kingsford Avenue, Glasgow G44 3EU 0141 416 1040 hello@fuzzylime.co.uk www.fuzzylime.co.uk Your email A setup guide Last updated March 7, 2017

CISC-124. Casting. // this would fail because we can t assign a double value to an int // variable

CISC-124 20180122 Today we looked at casting, conditionals and loops. Casting Casting is a simple method for converting one type of number to another, when the original type cannot be simply assigned to

School of Computer Science CPS109 Course Notes 5 Alexander Ferworn Updated Fall 15

Table of Contents 1 INTRODUCTION... 1 2 IF... 1 2.1 BOOLEAN EXPRESSIONS... 3 2.2 BLOCKS... 3 2.3 IF-ELSE... 4 2.4 NESTING... 5 3 SWITCH (SOMETIMES KNOWN AS CASE )... 6 3.1 A BIT ABOUT BREAK... 7 4 CONDITIONAL

CS1102: Adding Error Checking to Macros

CS1102: Adding Error Checking to Macros Kathi Fisler, WPI October 8, 2004 1 Typos in State Machines The point of creating macros for state machines is to hide language details from the programmer. Ideally,

Understanding Recursion

Understanding Recursion Brian L. Stuart February 23, 2015 It has been suggested that the single most original contribution that the field of Computer Science has made to the tapestry of human intellect

Control, Quick Overview. Selection. Selection 7/6/2017. Chapter 2. Control

Chapter 2 Control, Quick Overview Control Selection Selection Selection is how programs make choices, and it is the process of making choices that provides a lot of the power of computing 1 Python if statement

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 1/9/ Review. Here s a simple C++ program:

Welcome Back CSCI 262 Data Structures 2 - Review What you learned in CSCI 261 (or equivalent): Variables Types Arrays Expressions Conditionals Branches & Loops Functions Recursion Classes & Objects Streams

Introduction to Programming with JES

Introduction to Programming with JES Titus Winters & Josef Spjut October 6, 2005 1 Introduction First off, welcome to UCR, and congratulations on becoming a Computer Engineering major. Excellent choice.

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

Divisibility Rules and Their Explanations

Divisibility Rules and Their Explanations Increase Your Number Sense These divisibility rules apply to determining the divisibility of a positive integer (1, 2, 3, ) by another positive integer or 0 (although

3 ADT Implementation in Java

Object-Oriented Design Lecture 3 CS 3500 Spring 2010 (Pucella) Tuesday, Jan 19, 2010 3 ADT Implementation in Java Last time, we defined an ADT via a signature and a specification. We noted that the job

Drawing Hands, by M. C. Escher (lithograph, 1948)

Drawing Hands, by M. C. Escher (lithograph, 1948) 12 The Leap of Faith In the combining method, we build up to a recursive procedure by writing a number of special-case nonrecursive procedures, starting

(Refer Slide Time: 06:01)

Data Structures and Algorithms Dr. Naveen Garg Department of Computer Science and Engineering Indian Institute of Technology, Delhi Lecture 28 Applications of DFS Today we are going to be talking about

Project 5 - The Meta-Circular Evaluator

MASSACHVSETTS INSTITVTE OF TECHNOLOGY Department of Electrical Engineering and Computer Science 6.001 Structure and Interpretation of Computer Programs Fall Semester, 2005 Project 5 - The Meta-Circular

Lecture 16: HashTables 10:00 AM, Mar 2, 2018

CS18 Integrated Introduction to Computer Science Fisler, Nelson Lecture 16: HashTables 10:00 AM, Mar 2, 2018 Contents 1 Speeding up Lookup 1 2 Hashtables 2 2.1 Java HashMaps.......................................

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

Lab 7: OCaml 12:00 PM, Oct 22, 2017

CS17 Integrated Introduction to Computer Science Hughes Lab 7: OCaml 12:00 PM, Oct 22, 2017 Contents 1 Getting Started in OCaml 1 2 Pervasives Library 2 3 OCaml Basics 3 3.1 OCaml Types........................................

COSC 2P95. Procedural Abstraction. Week 3. Brock University. Brock University (Week 3) Procedural Abstraction 1 / 26

COSC 2P95 Procedural Abstraction Week 3 Brock University Brock University (Week 3) Procedural Abstraction 1 / 26 Procedural Abstraction We ve already discussed how to arrange complex sets of actions (e.g.

Homework 6: Higher-Order Procedures Due: 10:00 PM, Oct 17, 2017

Integrated Introduction to Computer Science Hughes Homework 6: Higher-Order Procedures Due: 10:00 PM, Oct 17, 2017 Contents 1 Fun with map (Practice) 2 2 Unfold (Practice) 3 3 Map2 3 4 Fold 4 5 All You

CS 342 Lecture 7 Syntax Abstraction By: Hridesh Rajan

CS 342 Lecture 7 Syntax Abstraction By: Hridesh Rajan 1 Reading SICP, page 11-19, Section 1.1.6 Little Schemer, Chapter 2 2 The Idea of Syntax Abstraction Problem. Often programming tasks are repetitive,

This book is about using Visual Basic for Applications (VBA), which is a

In This Chapter Describing Access Discovering VBA Seeing where VBA lurks Understanding how VBA works Chapter 1 Where VBA Fits In This book is about using Visual Basic for Applications (VBA), which is a

5 R1 The one green in the same place so either of these could be green.

Page: 1 of 20 1 R1 Now. Maybe what we should do is write out the cases that work. We wrote out one of them really very clearly here. [R1 takes out some papers.] Right? You did the one here um where you

Word: Print Address Labels Using Mail Merge

Word: Print Address Labels Using Mail Merge No Typing! The Quick and Easy Way to Print Sheets of Address Labels Here at PC Knowledge for Seniors we re often asked how to print sticky address labels in

Statistics Case Study 2000 M. J. Clancy and M. C. Linn

Statistics Case Study 2000 M. J. Clancy and M. C. Linn Problem Write and test functions to compute the following statistics for a nonempty list of numeric values: The mean, or average value, is computed

GDB Tutorial. A Walkthrough with Examples. CMSC Spring Last modified March 22, GDB Tutorial

A Walkthrough with Examples CMSC 212 - Spring 2009 Last modified March 22, 2009 What is gdb? GNU Debugger A debugger for several languages, including C and C++ It allows you to inspect what the program

MITOCW watch?v=rvrkt-jxvko

MITOCW watch?v=rvrkt-jxvko The following content is provided under a Creative Commons license. Your support will help MIT OpenCourseWare continue to offer high quality educational resources for free. To

Errors. Lecture 6. Hartmut Kaiser hkaiser/fall_2011/csc1254.html

Hartmut Kaiser hkaiser@cct.lsu.edu http://www.cct.lsu.edu/ hkaiser/fall_2011/csc1254.html 2 Abstract When we program, we have to deal with errors. Our most basic aim is correctness, but we must deal with

Type Checking and Type Equality

Type Checking and Type Equality Type systems are the biggest point of variation across programming languages. Even languages that look similar are often greatly different when it comes to their type systems.

Functions and Decomposition

Unit 4 Functions and Decomposition Learning Outcomes Design and implement functions to carry out a particular task. Begin to evaluate when it is necessary to split some work into functions. Locate the

CS1102: Macros and Recursion

CS1102: Macros and Recursion Kathi Fisler, WPI October 5, 2009 This lecture looks at several more macro examples. It aims to show you when you can use recursion safely with macros and when you can t. 1

;;; Determines if e is a primitive by looking it up in the primitive environment. ;;; Define indentation and output routines for the output for

Page 1/11 (require (lib "trace")) Allow tracing to be turned on and off (define tracing #f) Define a string to hold the error messages created during syntax checking (define error msg ""); Used for fancy