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

Size: px
Start display at page:

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

Transcription

1 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 OCaml Types OCaml Syntax OCaml Loves Types and So Should You Options (Not Optional) 4 5 The Design Recipe, in OCaml! Design Recipe for Atomic Data List Recursion 7 Objectives By the end of this lab, you will know: ˆ OCaml types ˆ OCaml syntax ˆ how and when to use options By the end of this lab, you will be able to: ˆ use Atom and compile OCaml code on the command line ˆ write recursive procedures based on built-in recursive types like lists ˆ write recursive procedures based on user-defined variant types ˆ pattern match in Ocaml

2 1 Getting Started in OCaml So far in CS 17, we ve written and run all our code in an Integrated Development Environment, or IDE. This means that we could run our code within the window that we were writing it in. But sadly, as we move on to OCaml, we have to say good bye to our friend DrRacket. Instead, we will be writing our code in the text editor Atom, and then running it from the command line! To get started, open up the terminal, and type atom & at the prompt. Wait a few seconds for Atom to load, and then mouse over the Atom window to activate it. Note: Before we move on, please configure your Atom to allow for OCaml syntax highlighting. Look at the OCaml installation guide on the website for help. Now you can either open an existing OCaml file or create a new one. Since you don t yet have any existing OCaml files, let s go ahead and create one. Type in the following lines of code: let a = 17 ;; let b = a ;; a + b ;; To save your program to a file, type Ctrl s. Give it an informative name, such as test.ml. (All OCaml files should end with the extension.ml.) You ll notice at this point that the colors of your text changed! This happened because Atom has intelligent syntax highlighting, meaning the editor will informatively color different parts of your program to make it easier for you to code and debug. Now, let s return to your terminal window and run your program. Note that in order to run your program from the command line, you need to first navigate into the directory in which your file is saved. 1. To check if your code has any syntax errors, you can run ocaml test.ml. If your code is error-free, this will output nothing! Otherwise, it provides a useful way to hunt down syntax errors in your code before moving on. 2. You can then run your code like this: ocaml < test.ml. Use this option when you want to see what your program outputs (e.g. the results of your test cases). 3. Alternatively, you can run the OCaml REPL, or Read-Evaluate-Print-Loop, yourself, by entering ocaml on the command line. Then, type #use "test.ml" ;; - this will read your program and evaluate each top level expression. You can also type OCaml procedures directly into the REPL to see what they will output. Don t forget the quotation marks (or the two semi-colons)! To exit from the OCaml interpreter, type either Ctrl-d or exit 1 ;;. Going back to your test.ml file, let s try entering a bad program. We might, for example, refer to a procedure that doesn t yet exist: factorial 5 ;; 2

3 After typing this in, let s check for syntax errors by entering ocaml test.ml into the terminal. You should now see an error message showing what caused the problem. You should also see a line indicating which line contains the error. Let s try something else, like making a spelling mistake: let five = 5 ;; fvie + 6 ;; Again, you will see a similar error message, but at the end, it will also ask you Did you mean five Whenever you finish writing a program, make sure to save it, and then exit Atom by closing your Atom window (Ctrl q). 2 Pervasives Library OCaml has lots of procedures and types predefined for you to use. Most of them are contained in libraries. To make use of procedures defined in libraries, you need to use a directive, a command that tells OCaml to import the library. There is one exception, however: the Pervasives library is preloaded when you start OCaml, so the definitions in that library are immediately accessible. The Pervasives Library, in essence, contains the procedures that you can use without defining them yourselves ( OCaml Builtins, so to speak). You can find out which procedures are defined for you here: Note: When you start up OCaml, you will see what looks like an error message, and says The files /course/cs017/src/ocaml/cs17setup.cmo and /local/bin/ocaml disagree over interface Pervasives. This is because we have modified some procedures (like + and * ) so that their behavior is safer for people new to programming. You can safely ignore this message. 3 OCaml Basics Before we begin, make sure to include our OCaml setup at the top of all of your assignments to make sure you have access to all of our functions. To get the CS17 OCaml version of a teachpack, first run the following command from the directory in which you are working: cp /course/cs0170/src/ocaml/cs17setup.ml. This will copy the teachpack to your current directory. Then include the following line at the top of your file #use "CS17setup.ml" ;; Note that you will need to do this at the top of all of your OCaml assignments! 3

4 3.1 OCaml Types Task: For each OCaml expression below, state the type of its value (not its value). For example, 3 has the value 3, but the type int. Some other OCaml types include float and string. If there is a type clash, meaning the expression s type is not well-defined, explain why. Please use the OCaml interpreter only to check your answers / 2 5. fun x ->x / [1; 2; [3; 4]] 7. (17, ["shiba"; "labrador"; "pug"; "corgi"], (false, true)) 8. [(1, 2, []); (3, 4, [5; 6; 7])] 9. if test then 1 else false 10. let rec count_pupper alod = match alod with [] - > 0 "pupper" :: tail - > 1 + count_pupper tail _ :: tail - > count_pupper tail 3.2 OCaml Syntax Task: Below, we have given you some expressions in Racket. Convert them to OCaml, and then execute them by running ocaml to ensure that your code is correct. When writing fibonacci, you may find it useful to use the OCaml when keyword, which checks a condition in a match case. An example of when usage can be found in the code for factorial in the next section of the lab. ( ) (* ( ) ( - 4 3)) (define (list - length alod) (cond [(empty? alod) 0] [(cons? alod) (+ 1 (list - length (rest alod)))])) (define (fibonacci x) (cond [(<= x 1) 1] [(> x 1) (+ (fibonacci ( - x 1)) (fibonacci ( - x 2)))])) 4

5 3.3 OCaml Loves Types and So Should You Unlike Racket, OCaml is a statically typed language. This means that OCaml will produce an error or refuse to read and print if the argument passed does not match the expected type. Clarifying your types helps the user of your function to know what types of arguments to put in and what order they go. This is analogous to the type signatures you wrote in Racket. For example: let rec factorial (x: int) : int = match x with x when x <= 1 - > 1 _ - > x * factorial (x - 1) ;; requires that you give factorial an int. If you give it a float, or any other type for that matter, it will throw an error. Note: We require you to type annotate all of your aguments and return types. 4 Options (Not Optional) Options are an important example of a parameterized variant type that is built in to OCaml: type 'a option = None Some of 'a In words, an 'a option is either a None or a Some applied to an argument of type 'a. Options are useful when writing a procedure that might not produce a value, such as a procedure that looks up a word in a dictionary, since that word might not be in the dictionary! Formally, a dictionary is a set of key-value pairs. For instance, in an English language dictionary, the keys are words and the values are the corresponding definitions. If you look up a word that is in the dictionary, then what you find is the corresponding definition. But if you look up a word that is not in the dictionary, then you don t find anything at all. What should a procedure that looks up keys in a dictionary produce when the key is not found? One possibility is the string "key not found". But what if there is a word in the dictionary whose definition is precisely "key not found"? If such a definition is possible, how could you distinguish between a successful and an unsuccessful lookup? A better alternative for when lookup fails is to produce a special value that cannot possibly be confused with a definition this is exactly what options allow you to do. Here is a data definition for dictionaries: type ('a, 'b) dict = ('a * 'b) list ;; (* Examples of dict *) [(1, 1); (2, 4); (3, 9); (4, 16)] ;; [(1, "one"); (2, "two"); (3, "three")] ;; 5

6 Task: Write a procedure, lookup, which consumes a dictionary and a key, and produces an option on the corresponding value. Examples: lookup [(1, 1); (2, 4); (3, 9); (4, 16)] 3 => Some 9 lookup [(1, "one"); (2, "two"); (3, "three")] 2 => Some "two" lookup [(1, "one"); (2, "two"); (3, "three")] 4 => None You ve reached a checkpoint! Please call over a lab TA to review your work. 5 The Design Recipe, in OCaml! In this part of the lab, we will review the design recipe for atomic data and the design recipe for mixed data, applying the exact same recipe as before while programming (the exact same procedures as before). 5.1 Design Recipe for Atomic Data The design recipe carries over more or less exactly from one programming language to another. The only difference between applying it to OCaml, as compared to Racket, is that the type signature does not appear in a comment. Instead, it appears as actual code. In particular, the call structure of every procedure you write in OCaml should be annotated with the types it consumes and the type it produces. For example, here is the call structure together with the type signature for the flip procedure in OCaml: let flip (alop : string*string list) : string*string list =... As for testing, your old friends check_expect, and a new tool, check_within are available for all your testing needs! You can use check_within to check the value of floats. To use check_within, pass in the procedure and its arguments, the expect result, and the tolerance, i.e. the decimal value to which we want to test the accuracy. In OCaml, they have underscores instead of hyphens, and are used like this: check_expect actual expected check_within actual expected within For example, here s the flip procedure in OCaml, developed by following the design recipe. Notice how much shorter it is than its Racket counterpart, because we can use tuples! 6

7 #use "CS17setup.ml" ;; (* Inputs: a list of pairs of strings, alop *) (* Output: a list where the ith element is in the same position, but the order of its elements is reversed *) let rec flip (alop : (string*string) list) : (string*string) list = match alop with [] - > [] (a, b) :: tail - > (b, a) :: (flip tail) ;; "Test cases for flip" ;; check_expect (flip []) [] ;; check_expect (flip [("hello", "world")]) [("world", "hello")] ;; check_expect (flip [("i", "love"); ("ocaml", "programming")]) [("love", "i"); ("programming", "ocaml")] ;; Task: Follow the design recipe to implement a procedure that converts degrees in Fahrenheit to degrees in Celsius. Hint: C = 5 9 (F 32), where C denotes degrees in Celsius, and F, degrees in Fahrenheit. You ve reached a checkpoint! Please call over a lab TA to review your work. 6 List Recursion In programming, as in natural languages, when one learns a new language, the tendency at first is to try to write programs in an old language, and then translate those programs into the new one. Sometimes this fails outright; more often it is possible, but bad style. We d like you to avoid the temptation to write Racket programs in OCaml. So in this problem we are explicitly forbidding the use of List.hd and List.tl, OCaml s equivalent of first and rest. You must use pattern matching instead. Here is the template for writing procedures that recur on lists in OCaml: let rec proc (alod : 'a list): <return - type> = match alod with [] - > head :: tail - >... head... (proc tail)... And here is the familiar length procedure: let rec length (alod : 'a list) : int = match alod with [] - > 0 _ :: tail - > 1 + length tail Task: Write the familiar procedure sum_list in OCaml. This procedure consumes a list of ints and produces the sum of the ints in that list. 7

8 Task: Rewrite sum_list using List.fold_right (or List.fold_left). 1 Hint: Here s how to get started: let sum_list alon = List.fold_right... Since sum_list applies to a list of integers, its type is int list ->int. Likewise, it is possible to apply List.fold_right to a few, but not all, of its arguments until its type is also int list ->int. Task: Define a type, base, that has one of four values "A", "C", "G", "T". Task: Write a procedure, complement, that takes in a base and returns its complement. Note: "A" and "T" are complements of each other, and "C" and "G" are complements of each other. Task: Write the procedure memberp : 'a * 'a list ->bool, which consumes a tuple consisting of a datum and a list of data, and determines whether that datum is in that list. For example: memberp (3, [1; 2; 3; 4; 5]) => true Note: In OCaml, you cannot use? to distinguish predicates, because the? character is reserved for another use. As a refresher, a predicate is a one-argument procedure that returns a boolean, such as even? or empty? in Racket. An alternative is to append a P to the end of the predicate s name: e.g., memberp. The P stands for predicate. You are at the grocery store, shopping for fruit. You want apples, bananas, and oranges, each of which is only purchaseable in a group (you cannot buy individual fruits). You get to the checkout, and want to know how many items are in your basket. Task: Define a type, fruit, that has an int parameter. There will be three types, apple, orange, and banana. Task: Write a procedure, num-fruits, that takes in a list of fruits and outputs the total number of fruits in the list. For example, a list of apple(3), banana(4) should output the integer 7. Task: Challenge (Time Permitting): Implement fold in OCaml. Once a lab TA signs off on your work, you ve finished the lab! Congratulations! Before you leave, make sure both partners have access to the code you ve just written. Please let us know if you find any mistakes, inconsistencies, or confusing language in this or any other CS17document by filling out the anonymous feedback form: courses/cs017/feedback. 1 You will learn the difference between these two procedures soon enough! 8

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

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

More information

Homework 8: Matrices Due: 11:59 PM, Oct 30, 2018

Homework 8: Matrices Due: 11:59 PM, Oct 30, 2018 CS17 Integrated Introduction to Computer Science Klein Homework 8: Matrices Due: 11:59 PM, Oct 30, 2018 Contents 1 Reverse (Practice) 4 2 Main Diagonal (Practice) 5 3 Horizontal Flip 6 4 Vertical Flip

More information

Lab 10: OCaml sequences, comparators, stable sorting 12:00 PM, Nov 12, 2017

Lab 10: OCaml sequences, comparators, stable sorting 12:00 PM, Nov 12, 2017 Integrated Introduction to Computer Science Hughes Lab 10: OCaml sequences, comparators, stable sorting 12:00 PM, Nov 12, 2017 Contents 1 A last OCaml type, and its utility 1 1.1 Sequences in OCaml....................................

More information

Homework 6: Higher-Order Procedures Due: 11:59 PM, Oct 16, 2018

Homework 6: Higher-Order Procedures Due: 11:59 PM, Oct 16, 2018 Integrated Introduction to Computer Science Klein Homework 6: Higher-Order Procedures Due: 11:59 PM, Oct 16, 2018 Contents 1 Fun with map (Practice) 2 2 Unfold (Practice) 3 3 Map2 3 4 Fold 4 5 All You

More information

The Design Recipe Fall 2017

The Design Recipe Fall 2017 CS17 Integrated Introduction to Computer Science Hughes The Design Recipe Fall 2017 Contents 1 Design Recipe Steps 1 2 An OCaml Example 6 1 Design Recipe Steps This PDF outlines the steps to writing the

More information

(Provisional) Lecture 08: List recursion and recursive diagrams 10:00 AM, Sep 22, 2017

(Provisional) Lecture 08: List recursion and recursive diagrams 10:00 AM, Sep 22, 2017 Integrated Introduction to Computer Science Hughes (Provisional) Lecture 08: List recursion and recursive diagrams 10:00 AM, Sep 22, 2017 Contents 1 Announcements 1 2 Evaluation Correction 1 3 Lists 2

More information

The Design Recipe Fall 2018

The Design Recipe Fall 2018 CS17 Integrated Introduction to Computer Science Klein The Design Recipe Fall 2018 Contents 1 Design Recipe Steps 1 2 Another Racket Example 6 3 An OCaml Example 6 4 Another OCaml Example 8 1 Design Recipe

More information

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

(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

More information

Homework 3: Recursion Due: 11:59 PM, Sep 25, 2018

Homework 3: Recursion Due: 11:59 PM, Sep 25, 2018 CS17 Integrated Introduction to Computer Science Klein Homework 3: Recursion Due: 11:59 PM, Sep 25, 2018 Contents 1 Factorial 3 2 Fibonacci 4 3 Odds Only 5 4 Increment All 6 5 Frequency 6 6 Sublist 7 6.1

More information

Homework 7: Subsets Due: 11:59 PM, Oct 23, 2018

Homework 7: Subsets Due: 11:59 PM, Oct 23, 2018 CS17 Integrated Introduction to Computer Science Klein Contents Homework 7: Subsets Due: 11:59 PM, Oct 23, 2018 1 Bookends (Practice) 2 2 Subsets 3 3 Subset Sum 4 4 k-subsets 5 5 k-subset Sum 5 Objectives

More information

(Provisional) Lecture 20: OCaml Fun!

(Provisional) Lecture 20: OCaml Fun! CS17 Integrated Introduction to Computer Science Hughes (Provisional) Lecture 20: OCaml Fun! 10:00 AM, Oct 23, 2017 Contents 1 Dictionaries 1 2 Well-Ordering Proof Practice 3 3 Summary 5 Objectives By

More information

Lab 1: Setup 12:00 PM, Sep 10, 2017

Lab 1: Setup 12:00 PM, Sep 10, 2017 CS17 Integrated Introduction to Computer Science Hughes Lab 1: Setup 12:00 PM, Sep 10, 2017 Contents 1 Your friendly lab TAs 1 2 Pair programming 1 3 Welcome to lab 2 4 The file system 2 5 Intro to terminal

More information

How to Design Programs

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

More information

OCaml Style Guide Fall 2017

OCaml Style Guide Fall 2017 CS17 Integrated Introduction to Computer Science Hughes OCaml Style Guide Fall 2017 Contents 1 Introduction 1 2 Naming 1 3 Formatting 2 3.1 Indenting.......................................... 2 3.2 Line

More information

Racket Style Guide Fall 2017

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......................................

More information

Lecture 27: (PROVISIONAL) Insertion Sort, Selection Sort, and Merge Sort 10:00 AM, Nov 8, 2017

Lecture 27: (PROVISIONAL) Insertion Sort, Selection Sort, and Merge Sort 10:00 AM, Nov 8, 2017 Integrated Introduction to Computer Science Hughes Lecture 27: (PROVISIONAL) Insertion Sort, Selection Sort, and Merge Sort 10:00 AM, Nov 8, 2017 Contents 1 Program Structure and Data Structure 1 2 Sorting

More information

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

Intro. Scheme Basics. scm> 5 5. scm> 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

More information

Homework 12: Tail Recursion and Analysis Due: 11:59 PM, Dec 4, 2018

Homework 12: Tail Recursion and Analysis Due: 11:59 PM, Dec 4, 2018 Integrated Introduction to Computer Science Klein Homework 12: Tail Recursion and Analysis Due: 11:59 PM, Dec 4, 2018 Contents 1 Tail Recursion 2 1.1 Harmonic Numbers.....................................

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

Typed Racket: Racket with Static Types

Typed Racket: Racket with Static Types Typed Racket: Racket with Static Types Version 5.0.2 Sam Tobin-Hochstadt November 6, 2010 Typed Racket is a family of languages, each of which enforce that programs written in the language obey a type

More information

Working with recursion. From definition to template. Readings: HtDP, sections 11, 12, 13 (Intermezzo 2).

Working with recursion. From definition to template. Readings: HtDP, sections 11, 12, 13 (Intermezzo 2). 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

More information

Working with recursion

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

More information

Lecture 3: Recursion; Structural Induction

Lecture 3: Recursion; Structural Induction 15-150 Lecture 3: Recursion; Structural Induction Lecture by Dan Licata January 24, 2012 Today, we are going to talk about one of the most important ideas in functional programming, structural recursion

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

Introduction to Typed Racket. The plan: Racket Crash Course Typed Racket and PL Racket Differences with the text Some PL Racket Examples

Introduction to Typed Racket. The plan: Racket Crash Course Typed Racket and PL Racket Differences with the text Some PL Racket Examples Introduction to Typed Racket The plan: Racket Crash Course Typed Racket and PL Racket Differences with the text Some PL Racket Examples Getting started Find a machine with DrRacket installed (e.g. the

More information

CS115 - Module 10 - General Trees

CS115 - Module 10 - General Trees Fall 2017 Reminder: if you have not already, ensure you: Read How to Design Programs, Sections 15 and 16. Arithmetic Expressions Recall with binary trees we could represent an expression containing binary

More information

A First Look at ML. Chapter Five Modern Programming Languages, 2nd ed. 1

A First Look at ML. Chapter Five Modern Programming Languages, 2nd ed. 1 A First Look at ML Chapter Five Modern Programming Languages, 2nd ed. 1 ML Meta Language One of the more popular functional languages (which, admittedly, isn t saying much) Edinburgh, 1974, Robin Milner

More information

CS115 - Module 9 - filter, map, and friends

CS115 - Module 9 - filter, map, and friends Fall 2017 Reminder: if you have not already, ensure you: Read How to Design Programs, Intermezzo 3 (Section 18); Sections 19-23. Abstraction abstraction, n. 3a.... The process of isolating properties or

More information

CMSC 201 Fall 2016 Lab 09 Advanced Debugging

CMSC 201 Fall 2016 Lab 09 Advanced Debugging CMSC 201 Fall 2016 Lab 09 Advanced Debugging Assignment: Lab 09 Advanced Debugging Due Date: During discussion Value: 10 points Part 1: Introduction to Errors Throughout this semester, we have been working

More information

The name of our class will be Yo. Type that in where it says Class Name. Don t hit the OK button yet.

The name of our class will be Yo. Type that in where it says Class Name. Don t hit the OK button yet. Mr G s Java Jive #2: Yo! Our First Program With this handout you ll write your first program, which we ll call Yo. Programs, Classes, and Objects, Oh My! People regularly refer to Java as a language that

More information

Data type built into Python. Dictionaries are sometimes found in other languages as associative memories or associative arrays.

Data type built into Python. Dictionaries are sometimes found in other languages as associative memories or associative arrays. NETB 329 Lecture 4 Data Structures in Python Dictionaries Data type built into Python. Dictionaries are sometimes found in other languages as associative memories or associative arrays. 1 of 70 Unlike

More information

Lab 10: Sockets 12:00 PM, Apr 4, 2018

Lab 10: Sockets 12:00 PM, Apr 4, 2018 CS18 Integrated Introduction to Computer Science Fisler, Nelson Lab 10: Sockets 12:00 PM, Apr 4, 2018 Contents 1 The Client-Server Model 1 1.1 Constructing Java Sockets.................................

More information

Lecture 5: Implementing Lists, Version 1

Lecture 5: Implementing Lists, Version 1 CS18 Integrated Introduction to Computer Science Fisler, Nelson Lecture 5: Implementing Lists, Version 1 Contents 1 Implementing Lists 1 2 Methods 2 2.1 isempty...........................................

More information

CS131 Typed Lambda Calculus Worksheet Due Thursday, April 19th

CS131 Typed Lambda Calculus Worksheet Due Thursday, April 19th CS131 Typed Lambda Calculus Worksheet Due Thursday, April 19th Name: CAS ID (e.g., abc01234@pomona.edu): I encourage you to collaborate. collaborations below. Please record your Each question is worth

More information

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

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

More information

Functional abstraction

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

More information

CMSC 330: Organization of Programming Languages. Functional Programming with Lists

CMSC 330: Organization of Programming Languages. Functional Programming with Lists CMSC 330: Organization of Programming Languages Functional Programming with Lists CMSC330 Spring 2018 1 Lists in OCaml The basic data structure in OCaml Lists can be of arbitrary length Implemented as

More information

CMSC 330: Organization of Programming Languages. Functional Programming with Lists

CMSC 330: Organization of Programming Languages. Functional Programming with Lists CMSC 330: Organization of Programming Languages Functional Programming with Lists 1 Lists in OCaml The basic data structure in OCaml Lists can be of arbitrary length Implemented as a linked data structure

More information

Programming. We will be introducing various new elements of Python and using them to solve increasingly interesting and complex problems.

Programming. We will be introducing various new elements of Python and using them to solve increasingly interesting and complex problems. Plan for the rest of the semester: Programming We will be introducing various new elements of Python and using them to solve increasingly interesting and complex problems. We saw earlier that computers

More information

Python lab session 1

Python lab session 1 Python lab session 1 Dr Ben Dudson, Department of Physics, University of York 28th January 2011 Python labs Before we can start using Python, first make sure: ˆ You can log into a computer using your username

More information

Functions that return lists

Functions that return lists 342 Chapter 23 Functions that return lists If you did exercises 22.5.15 or 22.5.16, you ve already written some functions that return lists, but only in a very simple way: adding one new element to the

More information

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. 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

More information

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

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 8/19/ 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

More information

Tail Calls. CMSC 330: Organization of Programming Languages. Tail Recursion. Tail Recursion (cont d) Names and Binding. Tail Recursion (cont d)

Tail Calls. CMSC 330: Organization of Programming Languages. Tail Recursion. Tail Recursion (cont d) Names and Binding. Tail Recursion (cont d) CMSC 330: Organization of Programming Languages Tail Calls A tail call is a function call that is the last thing a function does before it returns let add x y = x + y let f z = add z z (* tail call *)

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

CS 321 Programming Languages

CS 321 Programming Languages CS 321 Programming Languages Intro to OCaml Lists Baris Aktemur Özyeğin University Last update made on Monday 2 nd October, 2017 at 19:27. Some of the contents here are taken from Elsa Gunter and Sam Kamin

More information

SNU Programming Language Theory

SNU Programming Language Theory SNU 4541.574 Programming Language Theory Polymorphism Polymorphism We encountered the concept of polymorphism very briefly last time. Let s look at it now in a bit more detail. # let rec last l = match

More information

Module 3: New types of data

Module 3: New types of data Module 3: New types of data Readings: Sections 4 and 5 of HtDP. A Racket program applies functions to values to compute new values. These new values may in turn be supplied as arguments to other functions.

More information

Lists. Prof. Clarkson Fall Today s music: "Blank Space" by Taylor Swift

Lists. Prof. Clarkson Fall Today s music: Blank Space by Taylor Swift Lists Prof. Clarkson Fall 2017 Today s music: "Blank Space" by Taylor Swift I could show you incredible things // Magic, madness, heaven, sin So it's gonna be forever // Or it's gonna go down in flames

More information

Lab 5: Java IO 12:00 PM, Feb 21, 2018

Lab 5: Java IO 12:00 PM, Feb 21, 2018 CS18 Integrated Introduction to Computer Science Fisler, Nelson Contents Lab 5: Java IO 12:00 PM, Feb 21, 2018 1 The Java IO Library 1 2 Program Arguments 2 3 Readers, Writers, and Buffers 2 3.1 Buffering

More information

Input, output, and sequence

Input, output, and sequence Chapter 29 Input, output, and sequence For this chapter, switch languages in DrRacket to Advanced Student Language. In the real world, we don t usually give a computer all the information it needs, all

More information

(Provisional) Lecture 32: Estimated Value, Minimax, Functional Data 10:00 AM, Nov 20, 2017

(Provisional) Lecture 32: Estimated Value, Minimax, Functional Data 10:00 AM, Nov 20, 2017 Integrated Introduction to Computer Science Hughes (Provisional) Lecture 32: Estimated Value, Minimax, Functional Data 10:00 AM, Nov 20, 2017 Contents 1 Estimated Value and Search Subtrees 1 2 Minimax

More information

CS50 Supersection (for those less comfortable)

CS50 Supersection (for those less comfortable) CS50 Supersection (for those less comfortable) Friday, September 8, 2017 3 4pm, Science Center C Maria Zlatkova, Doug Lloyd Today s Topics Setting up CS50 IDE Variables and Data Types Conditions Boolean

More information

CMSC 330: Organization of Programming Languages. Operational Semantics

CMSC 330: Organization of Programming Languages. Operational Semantics CMSC 330: Organization of Programming Languages Operational Semantics Notes about Project 4, Parts 1 & 2 Still due today (7/2) Will not be graded until 7/11 (along with Part 3) You are strongly encouraged

More information

Lecture 8: Iterators and More Mutation

Lecture 8: Iterators and More Mutation Integrated Introduction to Computer Science Fisler, Nelson Contents 1 Traversing Lists 1 2 Motivating Iterators 2 3 Writing an Iterator 3 4 Writing Sum with an Iterator 4 Objectives By the end of this

More information

For this chapter, switch languages in DrRacket to Advanced Student Language.

For this chapter, switch languages in DrRacket to Advanced Student Language. Chapter 30 Mutation For this chapter, switch languages in DrRacket to Advanced Student Language. 30.1 Remembering changes Suppose you wanted to keep track of a grocery shopping list. You could easily define

More information

Deferred operations. Continuations Structure and Interpretation of Computer Programs. Tail recursion in action.

Deferred operations. Continuations Structure and Interpretation of Computer Programs. Tail recursion in action. Deferred operations Continuations 6.037 - Structure and Interpretation of Computer Programs Mike Phillips (define the-cons (cons 1 #f)) (set-cdr! the-cons the-cons) (define (run-in-circles l) (+

More information

CSc 520 Principles of Programming Languages

CSc 520 Principles of Programming Languages CSc 520 Principles of Programming Languages 3: Scheme Introduction Christian Collberg collberg@cs.arizona.edu Department of Computer Science University of Arizona Copyright c 2005 Christian Collberg [1]

More information

VISUAL GUIDE to. RX Scripting. for Roulette Xtreme - System Designer 2.0. L J Howell UX Software Ver. 1.0

VISUAL GUIDE to. RX Scripting. for Roulette Xtreme - System Designer 2.0. L J Howell UX Software Ver. 1.0 VISUAL GUIDE to RX Scripting for Roulette Xtreme - System Designer 2.0 L J Howell UX Software 2009 Ver. 1.0 TABLE OF CONTENTS INTRODUCTION...ii What is this book about?... iii How to use this book... iii

More information

printf( Please enter another number: ); scanf( %d, &num2);

printf( Please enter another number: ); scanf( %d, &num2); CIT 593 Intro to Computer Systems Lecture #13 (11/1/12) Now that we've looked at how an assembly language program runs on a computer, we're ready to move up a level and start working with more powerful

More information

Repetition Through Recursion

Repetition Through Recursion Fundamentals of Computer Science I (CS151.02 2007S) Repetition Through Recursion Summary: In many algorithms, you want to do things again and again and again. For example, you might want to do something

More information

If Statements, For Loops, Functions

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

More information

CS115 INTRODUCTION TO COMPUTER SCIENCE 1. Additional Notes Module 5

CS115 INTRODUCTION TO COMPUTER SCIENCE 1. Additional Notes Module 5 CS115 INTRODUCTION TO COMPUTER SCIENCE 1 Additional Notes Module 5 Example my-length (Slide 17) 2 (define (my-length alos) [(empty? alos) 0] [else (+ 1 (my-length (rest alos)))])) (my-length empty) alos

More information

Scheme: Expressions & Procedures

Scheme: Expressions & Procedures Scheme: Expressions & Procedures CS F331 Programming Languages CSCE A331 Programming Language Concepts Lecture Slides Friday, March 31, 2017 Glenn G. Chappell Department of Computer Science University

More information

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming Intro to Programming Unit 7 Intro to Programming 1 What is Programming? 1. Programming Languages 2. Markup vs. Programming 1. Introduction 2. Print Statement 3. Strings 4. Types and Values 5. Math Externals

More information

Module 8: Local and functional abstraction

Module 8: Local and functional abstraction Module 8: Local and functional abstraction Readings: HtDP, Intermezzo 3 (Section 18); Sections 19-23. We will cover material on functional abstraction in a somewhat different order than the text. We will

More information

Spring CS Homework 3 p. 1. CS Homework 3

Spring CS Homework 3 p. 1. CS Homework 3 Spring 2018 - CS 111 - Homework 3 p. 1 Deadline 11:59 pm on Friday, February 9, 2018 Purpose CS 111 - Homework 3 To try out another testing function, check-within, to get more practice using the design

More information

CS 314 Principles of Programming Languages. Lecture 16

CS 314 Principles of Programming Languages. Lecture 16 CS 314 Principles of Programming Languages Lecture 16 Zheng Zhang Department of Computer Science Rutgers University Friday 28 th October, 2016 Zheng Zhang 1 CS@Rutgers University Class Information Reminder:

More information

CSE 130, Winter 2011: Final Examination

CSE 130, Winter 2011: Final Examination Name: ID : CSE 130, Winter 2011: Final Examination March 15, 2011 Do not start the exam until you are told to. This is a open-book, open-notes exam, but with no computational devices allowed (such as calculators/cellphones/laptops).

More information

CS558 Programming Languages

CS558 Programming Languages CS558 Programming Languages Winter 2017 Lecture 7b Andrew Tolmach Portland State University 1994-2017 Values and Types We divide the universe of values according to types A type is a set of values and

More information

MP 3 A Lexer for MiniJava

MP 3 A Lexer for MiniJava MP 3 A Lexer for MiniJava CS 421 Spring 2012 Revision 1.0 Assigned Wednesday, February 1, 2012 Due Tuesday, February 7, at 09:30 Extension 48 hours (penalty 20% of total points possible) Total points 43

More information

CSCI0170. Today s topics. Predicates Natural Number recursion Recursion Diagrams List recursion A first glance at the design recipe

CSCI0170. Today s topics. Predicates Natural Number recursion Recursion Diagrams List recursion A first glance at the design recipe CSCI0170 Predicates Natural Number recursion Recursion Diagrams List recursion A first glance at the design recipe Today s topics Lecture recorded; see course website. Predicates: things that test stuff

More information

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 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

More information

Hands-On Lab. Introduction to F# Lab version: Last updated: 12/10/2010. Page 1

Hands-On Lab. Introduction to F# Lab version: Last updated: 12/10/2010. Page 1 Hands-On Lab Introduction to Lab version: 1.0.0 Last updated: 12/10/2010 Page 1 CONTENTS OVERVIEW... 3 EXERCISE 1: TYPES IN... 4 Task 1 Observing Type Inference in... 4 Task 2 Working with Tuples... 6

More information

Case Study: Undefined Variables

Case Study: Undefined Variables Case Study: Undefined Variables CS 5010 Program Design Paradigms Bootcamp Lesson 7.4 Mitchell Wand, 2012-2017 This work is licensed under a Creative Commons Attribution-NonCommercial 4.0 International

More information

15-122: Principles of Imperative Computation, Fall 2015

15-122: Principles of Imperative Computation, Fall 2015 15-122 Programming 5 Page 1 of 10 15-122: Principles of Imperative Computation, Fall 2015 Homework 5 Programming: Clac Due: Thursday, October 15, 2015 by 22:00 In this assignment, you will implement a

More information

CS Lecture 6: Map and Fold. Prof. Clarkson Fall Today s music: Selections from the soundtrack to 2001: A Space Odyssey

CS Lecture 6: Map and Fold. Prof. Clarkson Fall Today s music: Selections from the soundtrack to 2001: A Space Odyssey CS 3110 Lecture 6: Map and Fold Prof. Clarkson Fall 2014 Today s music: Selections from the soundtrack to 2001: A Space Odyssey Review Features so far: variables, operators, let expressions, if expressions,

More information

Using the Zoo Workstations

Using the Zoo Workstations Using the Zoo Workstations Version 1.86: January 16, 2014 If you ve used Linux before, you can probably skip many of these instructions, but skim just in case. Please direct corrections and suggestions

More information

Lecture Programming in C++ PART 1. By Assistant Professor Dr. Ali Kattan

Lecture Programming in C++ PART 1. By Assistant Professor Dr. Ali Kattan Lecture 08-1 Programming in C++ PART 1 By Assistant Professor Dr. Ali Kattan 1 The Conditional Operator The conditional operator is similar to the if..else statement but has a shorter format. This is useful

More information

Language Proposal: tail

Language Proposal: tail Language Proposal: tail A tail recursion optimization language Some Wise Gal Team Roles Team Members UNIs Roles Sandra Shaefer Jennifer Lam Serena Shah Simpson Fiona Rowan sns2153 jl3953 ss4354 fmr2112

More information

CS 360: Programming Languages Lecture 10: Introduction to Haskell

CS 360: Programming Languages Lecture 10: Introduction to Haskell CS 360: Programming Languages Lecture 10: Introduction to Haskell Geoffrey Mainland Drexel University Thursday, February 5, 2015 Adapted from Brent Yorgey s course Introduction to Haskell. Section 1 Administrivia

More information

An Explicit Continuation Evaluator for Scheme

An Explicit Continuation Evaluator for Scheme Massachusetts Institute of Technology Course Notes 2 6.844, Spring 05: Computability Theory of and with Scheme February 17 Prof. Albert R. Meyer revised March 3, 2005, 1265 minutes An Explicit Continuation

More information

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

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

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

Finding and Fixing Bugs

Finding and Fixing Bugs C Finding and Fixing Bugs C.1 Introduction As you will quickly find the BUG is the pain of all programmers existence. This section looks at the most common types of BUGS and some of the strategies for

More information

COSE212: Programming Languages. Lecture 3 Functional Programming in OCaml

COSE212: Programming Languages. Lecture 3 Functional Programming in OCaml COSE212: Programming Languages Lecture 3 Functional Programming in OCaml Hakjoo Oh 2017 Fall Hakjoo Oh COSE212 2017 Fall, Lecture 3 September 18, 2017 1 / 44 Why learn ML? Learning ML is a good way of

More information

Programming Languages and Techniques (CIS120)

Programming Languages and Techniques (CIS120) Programming Languages and Techniques (CIS120) Lecture 10 February 5 th, 2016 Abstract types: sets Lecture notes: Chapter 10 What is the value of this expresssion? let f (x:bool) (y:int) : int = if x then

More information

Programming Languages and Techniques (CIS120)

Programming Languages and Techniques (CIS120) Programming Languages and Techniques () Lecture 9 January 31, 2018 Lists and Higher-order functions Lecture notes: Chapter 9 What is the type of this expresssion? [ (fun (x:int) -> x + 1); (fun (x:int)

More information

TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA

TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA 1 TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA Notes adapted from Introduction to Computing and Programming with Java: A Multimedia Approach by M. Guzdial and B. Ericson, and instructor materials prepared

More information

CMSC 330: Organization of Programming Languages. OCaml Imperative Programming

CMSC 330: Organization of Programming Languages. OCaml Imperative Programming CMSC 330: Organization of Programming Languages OCaml Imperative Programming CMSC330 Spring 2018 1 So Far, Only Functional Programming We haven t given you any way so far to change something in memory

More information

Animations involving numbers

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

More information

Lisp. Versions of LISP

Lisp. Versions of LISP Lisp Versions of LISP Lisp is an old language with many variants Lisp is alive and well today Most modern versions are based on Common Lisp LispWorks is based on Common Lisp Scheme is one of the major

More information

Typed Scheme: Scheme with Static Types

Typed Scheme: Scheme with Static Types Typed Scheme: Scheme with Static Types Version 4.1.1 Sam Tobin-Hochstadt October 5, 2008 Typed Scheme is a Scheme-like language, with a type system that supports common Scheme programming idioms. Explicit

More information

5. Control Statements

5. Control Statements 5. Control Statements This section of the course will introduce you to the major control statements in C++. These control statements are used to specify the branching in an algorithm/recipe. Control statements

More information

CSCI 2041: Pattern Matching Basics

CSCI 2041: Pattern Matching Basics CSCI 2041: Pattern Matching Basics Chris Kauffman Last Updated: Fri Sep 28 08:52:58 CDT 2018 1 Logistics Reading OCaml System Manual: Ch 1.4-1.5 Practical OCaml: Ch 4 Goals Code patterns Pattern Matching

More information

Module 5: Lists. Readings: HtDP, Sections 9, 10.

Module 5: Lists. Readings: HtDP, Sections 9, 10. Module 5: Lists Readings: HtDP, Sections 9, 10. Lists are the main tool used in Racket to work with unbounded data. As with conditional expressions and structures, the data definition for lists leads naturally

More information

Lecture: Functional Programming

Lecture: Functional Programming Lecture: Functional Programming This course is an introduction to the mathematical foundations of programming languages and the implementation of programming languages and language-based tools. We use

More information

List Functions, and Higher-Order Functions

List Functions, and Higher-Order Functions List Functions, and Higher-Order Functions Björn Lisper Dept. of Computer Science and Engineering Mälardalen University bjorn.lisper@mdh.se http://www.idt.mdh.se/ blr/ List Functions, and Higher-Order

More information

Lesson 10A OOP Fundamentals. By John B. Owen All rights reserved 2011, revised 2014

Lesson 10A OOP Fundamentals. By John B. Owen All rights reserved 2011, revised 2014 Lesson 10A OOP Fundamentals By John B. Owen All rights reserved 2011, revised 2014 Table of Contents Objectives Definition Pointers vs containers Object vs primitives Constructors Methods Object class

More information

The design recipe. Readings: HtDP, sections 1-5. (ordering of topics is different in lectures, different examples will be used)

The design recipe. Readings: HtDP, sections 1-5. (ordering of topics is different in lectures, different examples will be used) The design recipe Readings: HtDP, sections 1-5 (ordering of topics is different in lectures, different examples will be used) Survival and Style Guides CS 135 Winter 2018 02: The design recipe 1 Programs

More information