# CSCI-GA Final Exam

Save this PDF as:

Size: px
Start display at page:

## Transcription

1 CSCI-GA Final Exam Instructor: Thomas Wies Name: Sample Solution ID: You have 110 minutes time. There are 7 assignments and you can reach 110 points in total. You can solve the exercises directly on the exam sheet. If you need additional paper, ask the instructor. Do not forget to put your name and ID on every page that you hand in. assignment Σ Grade max. points points Good Luck! 1

2 Assignment 1 (a) Write a polymorphic ML function Programming in ML (25 Points) zip: a list * b list -> ( a * b) list that takes a pair of lists and zips it to a list of pairs. The following examples demonstrate the intended behavior of zip: - zip ([1,2,3], [4,5,6]); val it = [(1,4),(2,5),(3,6)] : (int * int) list - zip ([1,2], [4,5,6]); val it = [(1,4),(2,5)] : (int * int) list - zip ([1,2,3], [] : int list); val it = [] : (int * int) list Note that if the input lists do not have the same length, then the remaining elements of the longer list are dropped. Your function does not need to be tail-recursive. (10 Points) (b) Write a polymorphic ML function foldr2: ( a * b * c -> c) -> c -> a list * b list -> c that is similar to the ML function foldr but folds two lists together. For example, the following function uses foldr2 to compute the sum of products of two lists of integers: fun sumofproducts (xs, ys) = foldr2 (fn (x, y, s) => x * y + s) 0 (xs, ys) In particular, sumofproducts ([1,2,3],[4,5,6]) should expand to 1 * 4 + (2 * 5 + (3 * 6 + 0)) and sumofproducts ([1,2,3],[4,5]) should expand to 1 * 4 + (2 * 5 + 0) Similar to the function zip, the function foldr2 should discard the remaining elements of the longer list, if the two input lists are not of the same length. (10 Points) (c) Express the function zip using the function foldr2. (5 Points) 2

3 Solution to Assignment 1: (a) fun zip ([], _) = [] zip (_, []) = [] zip (x::xs, y::ys) = (x,y)::zip (xs,ys) fun foldr2 f acc ([], _) = acc foldr2 f acc (_, []) = acc foldr2 f acc (x::xs, y::ys) = f (x, y, foldr2 f acc (xs, ys)) (b) (c) fun zip (xs, ys) = foldr2 (fn (x,y,xys) => (x,y)::xys) [] (xs, ys) 3

4 Assignment 2 Type Checking and Type Inference (10 Points) Consider the following ML function declaration fun blurgh (x, y) = if x - y then x * y else x / y handle Div => "Error: Division by 0" This declaration is syntactically correct. However, it contains two type errors. Find and explain these errors. 4

5 Solution to Assignment 2: First error. The term x-y has either type int or type real, depending on how the interpreter resolves the overloaded arithmetic operations. Either way, the term following after the if in the conditional expression must be of type bool. Second error. The handler for the Div exception returns a value of type string. However, the if expression that is guarded by the handler returns a value of type int or real (again depending on how overloaded operators are resolved). Either way, the types are incompatible. In ML, an exception handler must always return a value of a type that is compatible with the type of the expression that it guards. 5

6 Assignment 3 Type Inhabitation (13 Points) Write polymorphic ML functions that satisfy the following type signatures: where ˆ a function f: a -> b -> a ˆ a function g: ( a -> b -> c) -> b -> a -> c ˆ a function h: ( a, b) sum * ( a -> c) * ( b -> c) -> c ˆ a function i: ( a, b * c) sum -> ( b, a) sum * ( c, a) sum datatype ( a, b) sum = L of a R of b Do not use recursion or explicit type annotations in your declarations. Remember that in ML type expressions, the type constructor * has higher precedence than the type constructor ->. ( Points) 6

7 Solution to Assignment 3: fun f a b = a fun g x b a = x a b fun h (L a, x, y) = x a h (R b, x, y) = y b fun i (L a) = (R a, R a) i (R (b, c)) = (L b, L c) 7

8 Assignment 4 Scala Traits and Dynamic Binding (18 Points) Consider the following Scala classes and traits: abstract class Term { def eval: Int trait Double extends Term { abstract override def eval = 2 * super.eval trait Increment extends Term { abstract override def eval = 1 + super.eval trait Nullify extends Term { abstract override def eval = 0 class Sum(x: Int, y: Int) extends Term { override def eval = x + y To which value does each of the following expressions evaluate (4 * 3 Points): (a) (new Sum(1,2)).eval (b) (new Sum(1,2) with Double with Increment).eval (c) (new Sum(1,2) with Increment with Double).eval (d) (new Sum(1,2) with Nullify with Increment).eval Explain your results. (6 Points) 8

9 Solution to Assignment 4: (a) 3. Here eval is bound to the eval method declared in the class Sum. (b) 7. Here eval is bound to the eval method declared in the trait Increment. This method calls the eval method of the class it is mixed in, which is the eval method of Double. This method, in turn, calls the eval method of Sum. The latter returns 3 which is rst multiplied by 2 and then incremented by 1. (c) 8. Here eval is bound to the eval method declared in the trait Double. This method calls the eval method of the class it is mixed in, which is the eval method of Increment. This method, in turn, calls the eval method of Sum. The latter returns 3 which is rst incremented by 1 and then multiplied by 2. (d) 1. Here eval is bound to the eval method declared in the trait Increment. This method calls the eval method of the class it is mixed in, which is the eval method of Nullify. The latter returns 0 immediately, which is then incremented by 1. 9

10 Assignment 5 Scala Generics (12 Points) Scala provides two traits Function1 and Function2 for objects representing unary and binary functions. They are dened as follows: trait Function1[-T1,+R] { abstract def apply(x: T1): R //... some other methods defined using apply trait Function2[-T1,-T2,+R] { abstract def apply(x: T1, y: T2): R //... some other methods defined using apply For example, we can dene an object Sum that extends Function2 as follows object Sum extends Function2[Int,Int,Int] { def apply(x: Int, y: Int) = x + y and then use it like this scala> Sum(3,4) res0: Int = 7 Write a trait CurriedFunction2 that is both a Function2 and a Function1 where the unary apply method of Function1 is the curried version of the binary apply method of Function2. For example, if we dene: object Sum extends CurriedFunction2[Int,Int,Int] { def apply(x: Int, y: Int) = x + y then we should be able to use the apply method of Sum also in its curried form: scala> Sum(3)(4) res1: Int = 7 Make sure that you provide the correct type parameters when you extend or mix in the traits Function2 and Function1. Also the variance annotations for the type parameters of CurriedFunction2 should be as general as possible. 10

11 Solution to Assignment 5: trait CurriedFunction2[-T1, -T2, +R] extends Function1[T1,Function1[T2,R]] with Function2[T1,T2,R] { def apply(x: T1) = (y: T2) => apply(x,y) The following solution also works: trait CurriedFunction2[-T1, -T2, +R] extends Function2[T1,T2,R] with Function1[T1,Function1[T2,R]] { def apply(x: T1) = (y: T2) => apply(x,y) 11

12 Assignment 6 Subtyping and Variances (12 Points) Consider the following two generic Scala classes: class CoVar[+T](x: T) { def method1: T = x def method2(y: T) : List[T] = List(x,y) class ContraVar[-T](x: T) { def method1: T = x def method2(y: T) : List[T] = List(x,y) The Scala compiler will reject both classes because at least one method in each class violates the variance annotation of the type parameter T of that class. (a) For each class, explain what these variance violations are. (6 Points) (b) Change each class such that the violations of variances are xed. You are not allowed to change any of the following: ˆ the variance annotation of the type parameter T; ˆ the type of the parameter x; ˆ the parameter names and bodies of the methods. However, you are allowed to introduce additional type parameters and type bounds, and change the argument and return types of methods. If you change any of the method types, they should remain as precise as possible (e.g., you are not allowed to use the types Any or Nothing). You might nd it more dicult to x the class ContraVar. Hint: introduce an additional type parameter for the whole class. (6 Points) 12

13 Solution to Assignment 6: (a) In the class CoVar the covariant type parameter T appears in contravariant position in the argument type of method method2. On the other hand, in the class ContraVar the contravariant type parameter T appears in covariant position in the result types of methods method1 and method2. (b) class CoVar[+T](x: T) { def method1: T = x def method2[u >: T](y: U) : List[U] = List(x,y) class ContraVar[+U, -T <: U](x: T) { def method1: U = x def method2(y: T) : List[U] = List(x,y) 13

14 Assignment 7 Exceptions and call/cc (20 Points) (a) Explain why it is useful to dene exceptions as classes in object oriented languages like C++, Java, and Scala. (4 Points) (b) Languages such as Java and Scala provide try-finally blocks for exception handling. What do they do and what are they used for? (4 Points) (c) How do exception handlers in functional languages like ML and Scala dier from those of imperative languages like C++ and Java? (4 Points) (d) Consider the following Scheme programs. evaluate to? ( Points) Which value does each of these programs (i) (+ 4 (call/cc (lambda (c) 1))) (ii) (+ (+ 1 2) (call/cc (lambda (c) (+ (+ 1 2) (c 5))))) (iii) (define (search return wanted? lst) (if (wanted? (car lst)) (return (car lst)) (search return wanted? (cdr lst)))) (define (fluffy lst) (+ 1 (call/cc (lambda (return) (search return (lambda (x) (> x 3)) lst))))) (fluffy ( )) You do not need to explain your results to get full credit. Though, you might want to explain how you obtained the result for a chance of receiving partial credit in case your answer is incorrect. 14

15 Solution to Assignment 7: (a) This allows to group exceptions based on their subtype relationship. For example, one can dene a common exception handler for all exceptions that are subclasses of a specic class. (b) The finally block is executed when control leaves the try block, no matter whether this is due to normal termination of the block or because an exception was thrown but not caught in the try block. This is useful, for example, to ensure that all resources (such as locks, le descriptors, network sockets etc.) that have been acquired for usage in the current control block are properly released before control exits this block (e.g., because a thrown exception was not caught). (c) Unlike in imperative languages, where exception handlers are statements, in functional languages exception handlers return values just like any other expression. The result value of the exception handler is also the result value of the expression that is guarded by the handler in the case that an exception is thrown and caught by the handler. In statically typed languages such as ML and Scala, the type of the exception handler therefore has to be compatible with the type of the expression that it guards. (d) (i) 5 (ii) 8 (iii) 5. The function search calls the passed continuation return with the rst list element that satises the given predicate. This is the element 4. The continuation then increments this value by 1. 15

Programming Paradigms, Fall 06 Multiple Choice Exam January 29, 2007, 10:00 11:15 ID Name Each of the following questions has exactly one correct answer. For each question, you may select one or more answers

### CSC324- TUTORIAL 5. Shems Saleh* *Some slides inspired by/based on Afsaneh Fazly s slides

CSC324- TUTORIAL 5 ML Shems Saleh* *Some slides inspired by/based on Afsaneh Fazly s slides Assignment 1 2 More questions were added Questions regarding the assignment? Starting ML Who am I? Shems Saleh

### CSE341 Spring 2016, Midterm Examination April 29, 2016

CSE341 Spring 2016, Midterm Examination April 29, 2016 Please do not turn the page until 10:30. Rules: The exam is closed-book, closed-note, etc. except for one side of one 8.5x11in piece of paper. Please

### CSci 4223 Principles of Programming Languages

CSci 4223 Principles of Programming Languages Lecture 11 Review Features learned: functions, tuples, lists, let expressions, options, records, datatypes, case expressions, type synonyms, pattern matching,

### Programming Languages Fall 2013

Programming Languages Fall 2013 Lecture 2: types Prof. Liang Huang huang@qc.cs.cuny.edu Recap of Lecture 1 functional programming vs. imperative programming basic Haskell syntax function definition lazy

### Inductive Data Types

Inductive Data Types Lars-Henrik Eriksson Functional Programming 1 Original slides by Tjark Weber Lars-Henrik Eriksson (UU) Inductive Data Types 1 / 42 Inductive Data Types Today Today New names for old

### How does ML deal with +?

How does ML deal with +? Moscow ML version 2.00 (June 2000) - op +; > val it = fn : int * int -> int - 1 + 1; > val it = 2 : int - 1.0 + 1.0; > val it = 2.0 : real - false + false;! Overloaded + cannot

### Overview. Elements of Programming Languages. Advanced constructs. Motivating inner class example

Overview Elements of Programming Languages Lecture 11: Object-oriented functional programming James Cheney University of Edinburgh October 30, 2017 We ve now covered: basics of functional programming (with

### Lecture 4: Higher Order Functions

Lecture 4: Higher Order Functions Søren Haagerup Department of Mathematics and Computer Science University of Southern Denmark, Odense September 26, 2017 HIGHER ORDER FUNCTIONS The order of a function

### A Brief Introduction to Standard ML

A Brief Introduction to Standard ML Specification and Verification with Higher-Order Logic Arnd Poetzsch-Heffter (Slides by Jens Brandt) Software Technology Group Fachbereich Informatik Technische Universität

### OBJECT ORIENTED PROGRAMMING USING C++ CSCI Object Oriented Analysis and Design By Manali Torpe

OBJECT ORIENTED PROGRAMMING USING C++ CSCI 5448- Object Oriented Analysis and Design By Manali Torpe Fundamentals of OOP Class Object Encapsulation Abstraction Inheritance Polymorphism Reusability C++

### Variables and Bindings

Net: Variables Variables and Bindings Q: How to use variables in ML? Q: How to assign to a variable? # let = 2+2;; val : int = 4 let = e;; Bind the value of epression e to the variable Variables and Bindings

### CO Java SE 8: Fundamentals

CO-83527 Java SE 8: Fundamentals Summary Duration 5 Days Audience Application Developer, Developer, Project Manager, Systems Administrator, Technical Administrator, Technical Consultant and Web Administrator

### CSE 130: Programming Languages. Polymorphism. Ranjit Jhala UC San Diego

CSE 130: Programming Languages Polymorphism Ranjit Jhala UC San Diego Q: What is the value of res? let f g = let x = 0 in g 2 let x = 100 let h y = x + y let res = f h (a) 0 (b) 2 (c) 100 (d) 102 (e) 12

### CSci 4223 Lecture 12 March 4, 2013 Topics: Lexical scope, dynamic scope, closures

CSci 4223 Lecture 12 March 4, 2013 Topics: Lexical scope, dynamic scope, closures 1 Lexical Scope SML, and nearly all modern languages, follow the Rule of Lexical Scope: the body of a function is evaluated

### General Computer Science (CH ) Fall 2016 SML Tutorial: Practice Problems

General Computer Science (CH08-320101) Fall 2016 SML Tutorial: Practice Problems November 30, 2016 Abstract This document accompanies the traditional SML tutorial in GenCS. It contains a sequence of simple

### Improving Scala's Safe Type-Level Abstraction

Seminar: Program Analysis and Transformation University of Applied Sciences Rapperswil Improving Scala's Safe Type-Level Abstraction Stefan Oberholzer, soberhol@hsr.ch Dez 2010 Abstract Scala cannot nd

### Monad Background (3A) Young Won Lim 11/18/17

Copyright (c) 2016-2017 Young W. Lim. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.2 or any later version published

### Conversion vs. Subtyping. Lecture #23: Conversion and Type Inference. Integer Conversions. Conversions: Implicit vs. Explicit. Object x = "Hello";

Lecture #23: Conversion and Type Inference Administrivia. Due date for Project #2 moved to midnight tonight. Midterm mean 20, median 21 (my expectation: 17.5). In Java, this is legal: Object x = "Hello";

### Semantic Analysis. CSE 307 Principles of Programming Languages Stony Brook University

Semantic Analysis CSE 307 Principles of Programming Languages Stony Brook University http://www.cs.stonybrook.edu/~cse307 1 Role of Semantic Analysis Syntax vs. Semantics: syntax concerns the form of a

### Types for References, Exceptions and Continuations. Review of Subtyping. Γ e:τ τ <:σ Γ e:σ. Annoucements. How s the midterm going?

Types for References, Exceptions and Continuations Annoucements How s the midterm going? Meeting 21, CSCI 5535, Spring 2009 2 One-Slide Summary Review of Subtyping If τ is a subtype of σ then any expression

### Lists. Michael P. Fourman. February 2, 2010

Lists Michael P. Fourman February 2, 2010 1 Introduction The list is a fundamental datatype in most functional languages. ML is no exception; list is a built-in ML type constructor. However, to introduce

### Types, Type Inference and Unification

Types, Type Inference and Unification Mooly Sagiv Slides by Kathleen Fisher and John Mitchell Cornell CS 6110 Summary (Functional Programming) Lambda Calculus Basic ML Advanced ML: Modules, References,

### List Processing in Ocaml

CS251 Programming Languages Handout # 14 Prof. Lyn Turbak February 2, 2007 Wellesley College List Processing in Ocaml Given a list of integers ns, suppose we want to return a new list of the same length

### # true;; - : bool = true. # false;; - : bool = false 9/10/ // = {s (5, "hi", 3.2), c 4, a 1, b 5} 9/10/2017 4

Booleans (aka Truth Values) Programming Languages and Compilers (CS 421) Sasa Misailovic 4110 SC, UIUC https://courses.engr.illinois.edu/cs421/fa2017/cs421a # true;; - : bool = true # false;; - : bool

### Introduction to Functional Programming in Haskell 1 / 56

Introduction to Functional Programming in Haskell 1 / 56 Outline Why learn functional programming? The essence of functional programming What is a function? Equational reasoning First-order vs. higher-order

### A quick introduction to SML

A quick introduction to SML CMSC 15300 April 9, 2004 1 Introduction Standard ML (SML) is a functional language (or higherorder language) and we will use it in this course to illustrate some of the important

### CSC324 Functional Programming Typing, Exceptions in ML

CSC324 Functional Programming Typing, Exceptions in ML Afsaneh Fazly 1 Winter 2013 1 with many thanks to Anya Tafliovich, Gerald Penn, Sheila McIlraith, Wael Aboelsaddat, Tony Bonner, Eric Joanis, Suzanne

CSci 450: Org. of Programming Languages Overloading and Type Classes H. Conrad Cunningham 27 October 2017 (after class) Contents 9 Overloading and Type Classes 1 9.1 Chapter Introduction.........................

### Polymorphic lambda calculus Princ. of Progr. Languages (and Extended ) The University of Birmingham. c Uday Reddy

06-02552 Princ. of Progr. Languages (and Extended ) The University of Birmingham Spring Semester 2016-17 School of Computer Science c Uday Reddy2016-17 Handout 6: Polymorphic Type Systems 1. Polymorphic

### CPSC 311, 2010W1 Midterm Exam #2

CPSC 311, 2010W1 Midterm Exam #2 2010/11/02 Page 1 of 18 CPSC 311, 2010W1 Midterm Exam #2 Name: Q1: 20 Student ID: Q2: 20 Signature (required; indicates agreement with rules below): Q3: 20 Q4: 20 Q5: 20

### Continuation Passing Style. Continuation Passing Style

161 162 Agenda functional programming recap problem: regular expression matcher continuation passing style (CPS) movie regular expression matcher based on CPS correctness proof, verification change of

Processadors de Llenguatge II Functional Paradigm II Pratt A.7 Robert Harper s SML tutorial (Sec II) Rafael Ramirez Dep Tecnologia Universitat Pompeu Fabra User-Defined Types How to define the new type.

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

### 02157 Functional Programming Tagged values and Higher-order list functions

Tagged values and Higher-order list functions nsen 1 DTU Informatics, Technical University of Denmark Tagged values and Higher-order list functions MRH 27/09/2012 Part I: Disjoint Sets An Example A shape

Overloading, Type Classes, and Algebraic Datatypes Delivered by Michael Pellauer Arvind Computer Science and Artificial Intelligence Laboratory M.I.T. September 28, 2006 September 28, 2006 http://www.csg.csail.mit.edu/6.827

### Programming Principles

Programming Principles Midterm Exam Friday, November 9th 2012 First Name: Last Name: Your points are precious, don t let them go to waste! Your Name Work that can t be attributed to you is lost: write

### The Hack programming language:

The Hack programming language: Types for PHP Andrew Kennedy Facebook Facebook s PHP Codebase 350,000 files >10,000,000 LoC (www.facebook.com & internally) 1000s of commits per day, 2 releases per day Anecdotally,

### Thanks! Review. Course Goals. General Themes in this Course. There are many programming languages. Teaching Assistants. John Mitchell.

1 CS 242 Thanks! Review John Mitchell Final Exam Wednesday Dec 8 8:30 11:30 AM Gates B01, B03 Teaching Assistants Mike Cammarano TJ Giuli Hendra Tjahayadi Graders Andrew Adams Kenny Lau Vishal Patel and

### CS558 Programming Languages

CS558 Programming Languages Fall 2016 Lecture 6a Andrew Tolmach Portland State University 1994-2016 Functional Programming An alternative paradigm to imperative programming First-class functions Emphasis

### PROGRAMMING IN HASKELL. Chapter 2 - First Steps

PROGRAMMING IN HASKELL Chapter 2 - First Steps 0 The Hugs System Hugs is an implementation of Haskell 98, and is the most widely used Haskell system; The interactive nature of Hugs makes it well suited

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

### Standard ML. Curried Functions. ML Curried Functions.1

Standard ML Curried Functions ML Curried Functions.1 Curried Functions Side Note: Infix function declaration o Curried Function declaration o Declaring via "fun" o Function Calling Order o Examples o Mixing

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

### Begin at the beginning

Begin at the beginning Expressions (Syntax) Exec-time Dynamic Values (Semantics) Compile-time Static Types 1. Programmer enters expression 2. ML checks if expression is well-typed Using a precise set of

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

### CS 6456 OBJCET ORIENTED PROGRAMMING IV SEMESTER/EEE

CS 6456 OBJCET ORIENTED PROGRAMMING IV SEMESTER/EEE PART A UNIT I 1. Differentiate object oriented programming from procedure oriented programming. 2. Define abstraction and encapsulation. 3. Differentiate

T O Y H Advances in Programming Languages APL8: Multiparameter Type Classes, Constructor Classes Ian Stark School of Informatics The University of Edinburgh Thursday 4 February Semester 2 Week 4 E H U

### Conformance. Object-Oriented Programming Spring 2015

Conformance Object-Oriented Programming 236703 Spring 2015 1 What s Conformance? Overriding: replace method body in sub-class Polymorphism: subclass is usable wherever superclass is usable Dynamic Binding:

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

### CS 360: Programming Languages Lecture 12: More Haskell

CS 360: Programming Languages Lecture 12: More Haskell Geoffrey Mainland Drexel University Adapted from Brent Yorgey s course Introduction to Haskell. Section 1 Administrivia Administrivia Homework 5 due

### The Typed Racket Guide

The Typed Racket Guide Version 6.9 Sam Tobin-Hochstadt ăsamth@racket-lang.orgą, Vincent St-Amour ăstamourv@racket-lang.orgą, Eric Dobson ăendobson@racket-lang.orgą, and Asumu Takikawa ăasumu@racket-lang.orgą

### CSE 505. Lecture #9. October 1, Lambda Calculus. Recursion and Fixed-points. Typed Lambda Calculi. Least Fixed Point

Lambda Calculus CSE 505 Lecture #9 October 1, 2012 Expr ::= Var λ Var. Expr (Expr Expr) Key Concepts: Bound and Free Occurrences Substitution, Reduction Rules: α, β, η Confluence and Unique Normal Form

### Operators. Lecture 3 COP 3014 Spring January 16, 2018

Operators Lecture 3 COP 3014 Spring 2018 January 16, 2018 Operators Special built-in symbols that have functionality, and work on operands operand an input to an operator Arity - how many operands an operator

### Lecture 3 Tao Wang 1

Lecture 3 Tao Wang 1 Objectives In this chapter, you will learn about: Arithmetic operations Variables and declaration statements Program input using the cin object Common programming errors C++ for Engineers

### User-Defined Algebraic Data Types

72 Static Semantics User-Defined Types User-Defined Algebraic Data Types An algebraic data type declaration has the general form: data cx T α 1... α k = K 1 τ 11... τ 1k1... K n τ n1... τ nkn introduces

### cs242 Kathleen Fisher Reading: Concepts in Programming Languages, Chapter 6 Thanks to John Mitchell for some of these slides.

cs242 Kathleen Fisher Reading: Concepts in Programming Languages, Chapter 6 Thanks to John Mitchell for some of these slides. We are looking for homework graders. If you are interested, send mail to cs242cs.stanford.edu

### low and not larger than high. 18 points

CSE 330 Test 1 (1 point) Spring 015 Multiple Choice. Write your answer to the LEFT of each problem. 3 points each 1. Lisp was invented at: A. IBM B. MIT C. Netscape D. Stanford. In C++, what operator is

### Operators & Expressions

Operators & Expressions Operator An operator is a symbol used to indicate a specific operation on variables in a program. Example : symbol + is an add operator that adds two data items called operands.

### Paytm Programming Sample paper: 1) A copy constructor is called. a. when an object is returned by value

Paytm Programming Sample paper: 1) A copy constructor is called a. when an object is returned by value b. when an object is passed by value as an argument c. when compiler generates a temporary object

### G Programming Languages - Fall 2012

G22.2110-003 Programming Languages - Fall 2012 Lecture 10 Thomas Wies New York University Review Last class ML Outline Modules Sources: PLP, 3.3.4, 3.3.5, 3.8 McConnell, Steve. Code Complete, Second Edition,

### Integrating Normalization-by-Evaluation. into a Staged Programming Language. Tim Sheard. Pacic Software Research Center. 2.2 The escape operator:

Integrating Normalization-by-Evaluation into a Staged Programming Language Tim Sheard Pacic Software Research Center Oregon Graduate Institute sheard@cse.ogi.edu 1 Introduction We have designed MetaML

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

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

### Consider the following EBNF definition of a small language:

xercise 1: Consider the following BNF definition of a small language: program ::= + decl ::= vardecl ::= "var" ":" "=" ";" procdecl ::= "procedure"

### Chapter 7. Expressions and Assignment Statements (updated edition 11) ISBN

Chapter 7 Expressions and Assignment Statements (updated edition 11) ISBN 0-321-49362-1 Chapter 7 Topics Introduction Arithmetic Expressions Overloaded Operators Type Conversions Relational and Boolean

### Homework 6. What To Turn In. Reading. Problems. Handout 15 CSCI 334: Spring, 2017

Homework 6 Due 11 April Handout 15 CSCI 334: Spring, 2017 What To Turn In Please hand in work in two pieces, one for the Problems and one for the Programming (Partner Optional): Problems: Turn in handwritten

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

CS 3110 Lecture 6: Map and Fold Prof. Clarkson Spring 2015 Today s music: Selections from the soundtrack to 2001: A Space Odyssey Review Course so far: Syntax and semantics of (most of) OCaml Today: No

### Software II: Principles of Programming Languages. Why Expressions?

Software II: Principles of Programming Languages Lecture 7 Expressions and Assignment Statements Why Expressions? Expressions are the fundamental means of specifying computations in a programming language

### Chapter 7. Expressions and Assignment Statements

Chapter 7 Expressions and Assignment Statements Chapter 7 Topics Introduction Arithmetic Expressions Overloaded Operators Type Conversions Relational and Boolean Expressions Short-Circuit Evaluation Assignment

### Tuples. CMSC 330: Organization of Programming Languages. Examples With Tuples. Another Example

CMSC 330: Organization of Programming Languages OCaml 2 Higher Order Functions Tuples Constructed using (e1,..., en) Deconstructed using pattern matching Patterns involve parens and commas, e.g., (p1,p2,

### Semantic Analysis. Outline. The role of semantic analysis in a compiler. Scope. Types. Where we are. The Compiler Front-End

Outline Semantic Analysis The role of semantic analysis in a compiler A laundry list of tasks Scope Static vs. Dynamic scoping Implementation: symbol tables Types Static analyses that detect type errors

### Bibliography. Analyse et Conception Formelle. Lesson 5. Crash Course on Scala. Scala in a nutshell. Outline

Bibliography Analyse et Conception Formelle Lesson 5 Crash Course on Scala Simply Scala. Onlinetutorial: http://www.simply.com/fr http://www.simply.com/ Programming in Scala, M. Odersky, L. Spoon, B. Venners.

### Week 5 Tutorial Structural Induction

Department of Computer Science, Australian National University COMP2600 / COMP6260 Formal Methods in Software Engineering Semester 2, 2016 Week 5 Tutorial Structural Induction You should hand in attempts

### Principles of Programming Languages (2016F)

03-60-440 Principles of Programming Languages (2016F) Jianguo Lu School of Computer Science University of Windsor It is about programming languages This course involves several programming languages: Scheme

### (Not Quite) Minijava

(Not Quite) Minijava CMCS22620, Spring 2004 April 5, 2004 1 Syntax program mainclass classdecl mainclass class identifier { public static void main ( String [] identifier ) block } classdecl class identifier

Advanced features of Functional Programming (Haskell) Polymorphism and overloading January 10, 2017 Monomorphic and polymorphic types A (data) type specifies a set of values. Examples: Bool: the type of

### Linked lists and the List class

Linked lists and the List class Cheong 1 Linked lists So far, the only container object we used was the array. An array is a single object that contains references to other objects, possibly many of them.

### CS110D: PROGRAMMING LANGUAGE I

CS110D: PROGRAMMING LANGUAGE I Computer Science department Lecture 5&6: Loops Lecture Contents Why loops?? While loops for loops do while loops Nested control structures Motivation Suppose that you need

### Lecture 19: Signatures, Structures, and Type Abstraction

15-150 Lecture 19: Signatures, Structures, and Type Abstraction Lecture by Dan Licata March 27, 2012 In these lectures, we will discuss the use of the ML module system for structuring large programs. Key

### Shell CSCE 314 TAMU. Functions continued

1 CSCE 314: Programming Languages Dr. Dylan Shell Functions continued 2 Outline Defining Functions List Comprehensions Recursion 3 A Function without Recursion Many functions can naturally be defined in

### Overview. Elements of Programming Languages. Another example. Consider the humble identity function

Overview Elements of Programming Languages Lecture 8: Polymorphism and type inference James Cheney University of Edinburgh October 21, 2016 This week and next week, we will cover di erent forms of abstraction

### Option Values, Arrays, Sequences, and Lazy Evaluation

Option Values, Arrays, Sequences, and Lazy Evaluation Björn Lisper School of Innovation, Design, and Engineering Mälardalen University bjorn.lisper@mdh.se http://www.idt.mdh.se/ blr/ Option Values, Arrays,

### Tail Recursion: Factorial. Begin at the beginning. How does it execute? Tail recursion. Tail recursive factorial. Tail recursive factorial

Begin at the beginning Epressions (Synta) Compile-time Static Eec-time Dynamic Types Values (Semantics) 1. Programmer enters epression 2. ML checks if epression is well-typed Using a precise set of rules,

### Type system. Type theory. Haskell type system. EDAN40: Functional Programming Types and Type Classes (revisited)

Type system EDAN40: Functional Programming Types and Type Classes (revisited) Jacek Malec Dept. of Computer Science, Lund University, Sweden April 3rd, 2017 In programming languages, a type system is a

### Programming language seminar The F# language. Peter Sestoft Wednesday Course plan

Programming language seminar 2011 The F# language Peter Sestoft Wednesday 2011-08-31 www.itu.dk 1 Course plan Four cycles, each containing a mini-project: F# Types and type inference Scala and Scala actors

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

### So what does studying PL buy me?

So what does studying PL buy me? Enables you to better choose the right language but isn t that decided by libraries, standards, and my boss? Yes. Chicken-and-egg. My goal: educate tomorrow s tech leaders

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

### Tree Oriented Programming. Jeroen Fokker

Tree Oriented Programming Jeroen Fokker Tree oriented programming Many problems are like: Input text transform process unparse Output text Tree oriented programming Many problems are like: Input text parse

### The Art of Recursion: Problem Set 10

The Art of Recursion: Problem Set Due Tuesday, November Tail recursion A recursive function is tail recursive if every recursive call is in tail position that is, the result of the recursive call is immediately

### Outline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring

Java Outline Java Models for variables Types and type checking, type safety Interpretation vs. compilation Reasoning about code CSCI 2600 Spring 2017 2 Java Java is a successor to a number of languages,

### Monad Background (3A) Young Won Lim 11/20/17

Copyright (c) 2016-2017 Young W. Lim. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.2 or any later version published

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

### Lecture 6: Sequential Sorting

15-150 Lecture 6: Sequential Sorting Lecture by Dan Licata February 2, 2012 Today s lecture is about sorting. Along the way, we ll learn about divide and conquer algorithms, the tree method, and complete

### Patterns The Essence of Functional Programming

Patterns The Essence of Functional Programming Up to now we have defined functions in a very traditional way: function name + variable name parameters Read Chap 7 In functional programming we can exploit