About coding style Spring February 9, 2004

Size: px
Start display at page:

Download "About coding style Spring February 9, 2004"

Transcription

1 About codg style Sprg 2004 February 9, 2004 Contents 1 Correctness 2 2 Specification 2 3 Style if-then- Expressions Boolean if-then- Expressions if-then- stead of Pattern Matchg Functions Multiple Evaluations Redefition of Library Functions Overly Complex Implementations Helper Functions Non-local Helper Functions Multiple Defitions of the Same Local Helper Function Pattern Matchg Redundant Cases Pattern Matchg Besides Function Arguments Bdgs to Identifiers and the Wildcard Pattern Multiple Patterns for Function Arguments Correspondg tothesameexpression ShadowgofPreviousBdgs

2 A few students have asked what are the style guideles for a perfect homework. First of all, the code the homework is graded based on three ma components: correctness, specification, andstyle. 1 Correctness Correctness refers to the correctness of the function that is implemented, i.e., if the function computes the value requested the homework handout. 2 Specification Specification refers to the presence and correctness of the specification a comment before the function: the comment must conta the identifier beg declared, its type, an explanation of the meang of the value computed, a list of variants, and a list of possible effects. It is very important for the specification to be present for all functions, global, auxiliary and local functions: you can refer to the code distributed on the course webpage for some examples. Very simple helper functions and lambda expressions may not have a specification: if the function is very simple its meang can be understood without the help of a specification. Use your judgment to decide if a specification is needed for a helper function, when doubt, provide the specification: you will reduce the risk of losg specification pots. 3 Style Style refers to the way you implemented the requested function: most functions can be implemented many different ways, each one of them satisfies the correctness requirement, but some of them have a better style. In specific, sce the ma focus of the course is functional programmg, a functional style is to be preferred. Moreover, general an elegant solution should be preferred to a more efficient one, if the more efficient solution is much more complicated. However do not write a very elegant O(2 n ) solution stead of a bit less elegant O(n) one! Sometimes we might ask to implement a function followg particular requirements (e.g., request a recursive defition): if there exists a more efficient solution that does not adhere to such requirements, please do not use such solution as it will not be considered a correct solution to the problem, as it does not satisfy the explicit requirements. Often exercises are meant to test the ability to use a particular programmg technique (like the use of recursive function defitions) and if the solution does not follow the given requirement, it won t be useful establishg the ability to use such technique. In terms of style, one of the purposes of homework #1 was to get familiar with the functional programmg style. The best sources for learng good programmg style are the example code presented at lectures and recitation as well as the code distributed on the course webpage. The followg contas 2

3 some example of bad style that you can use to understand what you should avoid, and what to do stead: 3.1 if-then- Expressions Boolean if-then- Expressions if a = b then true false It is bad style to have an if-then- expression whose type is bool. The previous expression is equivalent to a = b. Other examples clude: if a = b then false true is equivalent to: not (a = b) if a = b then if a > 0 then true false false is equivalent to: (a = b) andalso (a > 0) if a = b then true if a > 0 then true false is equivalent to: (a = b) or (a > 0) 3

4 3.1.2 if-then- stead of Pattern Matchg fun natpred (n: t) : t = if n = 0 then 0 n - 1 In this case, the if statement is used to discrimate over the value of an argument that is matched agast a constant. This should be done usg pattern matchg as follows: fun natpred (0: t) : t = 0 natpred (n: t) : t = n Functions Multiple Evaluations if f (x) > 0 then f (x) 0 In this case function f is evaluated twice. Sce f does not have side effects (you are not allowed to use the imperative features of SML), the function will return the same value each time. If is better style to do the followg: val y = f (x) if y > 0 then y 0 or: fun positiveorzero (n:t): t = if n > 0 then n 0 positiveorzero (f (x)) 4

5 The second solution is to be preferred especially if the function positiveorzero is reused other parts of the code ( which case it has to be scoped accordgly) Redefition of Library Functions val max: t * t -> t max (x,y) returns the maximum of two numbers. Invariants: none fun max (x: t, y: t): t = if x > y then x y val maxlist : t list -> t maxlist (l) computes the maximum value contaed the list Invariants: l is not empty and every element of l is positive. fun maxlist ([]: t list): t = 0 maxlist (x::xs: t list): t = max (x, maxlist (xs)) There is another additional improvement that should be done to this code. The function max is actually equivalent to the library function Int.max. In general, you should not defe your own function when an equivalent function is present the library. Library functions are described the SML base library documentation, moreover, some of the most commonly used functions are also summarized the appix of the textbook. Try to avoid re-ventg the wheel, and make full use of the library functions. This is especially true the case of library functions for lists, like foldl, foldr, andmap, which can often be used to produce a very simple and elegant function that accomplishes the given task. val maxlist : t list -> t maxlist (l) computes the maximum value contaed the list 5

6 Invariants: l is not empty and every element of l is positive. fun maxlist ([]: t list): t = 0 maxlist (x::xs: t list): t = Int.max (x, maxlist (xs)) Overly Complex Implementations val divisible : t * t -> bool divisible (n, m) returns true if n is divisible by m Invariants: n >= 0 and m > 0 fun divisible(n: t, m: t): bool = if n = m then true if n < m then false divisible (n - m, m) In this case, while the function is correct, the implementation is overly complex: a natural number n is divisible by a positive natural number m, ifthe remader of the division of n by m is equal to zero. The remader can be obtaed by usg the mod operator. Moreover, the previous implementation has complexity O(n/m), while the mod operation can be done constant time. A better solution would be: val divisible : t * t -> bool divisible (n, m) returns true if n is divisible by m Invariants: x and y are strictly positive fun divisible(n: t, m: t): bool = (n mod m) = Helper Functions Non-local Helper Functions 6

7 val maxlisthelper : t * t list -> t maxlisthelper (max, list) computes the maximum of max and each value the list Invariants: none fun maxlisthelper (max: t, []: t list): t = max maxlisthelper (max: t, x::xs: t list): t = val newmax: t = if max > x then max x maxlisthelper (newmax, xs) val maxlist : t list -> t maxlist (l) computes the maximum value contaed the list Invariants: l is not empty Effects: raises Invalid_argument if the list is empty fun maxlist ([]: t list): t = raise Invalid_argument maxlist (x::xs: t list): t = maxlisthelper (x, xs) In this case the maxlisthelper function is an auxiliary function that is used the defition of maxlist. Sce it has no specific use besides with maxlist, it should be defed as a local function. val maxlist : t list -> t maxlist (l) computes the maximum value contaed the list Invariants: l is not empty Effects: raises Invalid_argument if the list is empty The function maxlist uses the local helper function: 7

8 val maxlisthelper : t * t list -> t maxlisthelper (max, list) computes the maximum of max and each value the list Invariants: none fun maxlist ([]: t list): t = raise Invalid_argument maxlist (x::xs: t list): t = fun maxlisthelper (max: t, []: t list): t = max maxlisthelper (max: t, x::xs: t list): t = val newmax: t = if max > x then max x maxlisthelper (newmax, xs) maxlisthelper (x, xs) Multiple Defitions of the Same Local Helper Function val maxlist : t list -> t maxlist (l) computes the maximum value contaed the list Invariants: l is not empty and every element of l is positive. The function maxlist uses the local helper function: val max: t * t -> t max (x,y) returns the maximum of two numbers. Invariants: none 8

9 fun maxlist ([]: t list): t = 0 maxlist (x::xs: t list): t = fun max (x: t, y: t): t = if x > y then x y max (x, maxlist (xs)) val maxfun t * (t -> t) * (t -> t) -> t maxfun (x, f, g) returns the maximum of f(x) and g(x). Invariants: f and g are defed at x. The function maxfun uses the local helper function: val max: t * t -> t max (x,y) returns the maximum of two numbers. Invariants: none fun maxfun (x: t, f: t -> t, g: t -> t): t = fun max (x: t, y: t): t = if x > y then x y max (f (x), g (x)) In this case the function max: t * t -> t is defed as a local helper function both maxlist and maxfun. It is better style to defe max as a non local helper function, especially given the general nature of the function max. val max: t * t -> t max (x,y) returns the maximum of two numbers. Invariants: none 9

10 fun max (x: t, y: t): t = if x > y then x y val maxlist : t list -> t maxlist (l) computes the maximum value contaed the list Invariants: l is not empty and every element of l is positive. fun maxlist ([]: t list): t = 0 maxlist (x::xs: t list): t = max (x, maxlist (xs)) val maxfun t * (t -> t) * (t -> t) -> t maxfun (x, f, g) returns the maximum of f(x) and g(x). Invariants: f and g are defed at x. fun maxfun (x: t, f: t -> t, g: t -> t): t = max (f (x), g (x)) 3.4 Pattern Matchg Redundant Cases fun fib (0: t): t = 1 fib (1: t): t = 1 fib (2: t): t = 2 fib (n: t): t = fib(n-1) + fib(n-2) In this case the additional base case for n = 2 is not necessary. A better defition for the function fib would be: fun fib (0: t): t = 1 fib (1: t): t = 1 fib (n: t): t = fib(n-1) + fib(n-2) 10

11 3.4.2 Pattern Matchg Besides Function Arguments fun second (nil: t list) : t option = NONE second (x::nil: t list) : t option = NONE second (x::xs: t list) : t option = val second::rest : t list = xs SOME second In this case, the local defition is used to bd the second element of the list of the local variable second. While the code is correct and sometimes it is necessary to use pattern matchg besides function argument, this case this is not good style: the pattern matchg should have been done the argument pattern stead, makg it evident the tention. Moreover this approach works correctly only because the pattern (x::nil) appears before the pattern (x::xs). A better solution would be: fun second (nil: t list) : t option = NONE second (x::nil: t list) : t option = NONE second (x::second::rest: t list) : t option = SOME second Bdgs to Identifiers and the Wildcard Pattern fun second (nil: t list) : t option = NONE second (x::nil: t list) : t option = NONE second (x::second::rest: t list) : t option = SOME second The previous function declaration can be further improved by replacg bdgs the patterns to identifiers that are never used with the wildcard pattern. fun second (nil: t list) : t option = NONE second (_::nil: t list) : t option = NONE second (_::second::_: t list) : t option = SOME second Multiple Patterns for Function Arguments Correspondg to the Same Expression fun second (nil: t list) : t option = NONE second (_::nil: t list) : t option = NONE second (_::second::_: t list) : t option = SOME second 11

12 The pattern the previous defition is used only to discrimate between a list with at least 2 elements, and a list with fewer than 2 elements. The same result can be obtaed by the more compact: fun second (_::second::_: t list) : t option = SOME second second (_: t list) : t option = NONE Beware, however, that the use of the wildcard pattern as well as overlappg patterns (multiple pattern that can match the same value), can be sometimes misleadg. For stance, the last example and ::second:: both match the list [1,2,3]: however the first pattern will be the one chosen because it appears first. 3.5 Shadowg of Previous Bdgs fun convolve (1: t, f: t -> t, g: t -> t): t = f(1) * g(1) convolve (k: t, f: t -> t, g: t -> t): t = val f = fn (n: t) => f(n+1) f(0) * g(k) + convolve (k-1, f, g) The function convolve defes a bdg for f that overrides the previous bdg of f. In general, it is bad style to defe new bdgs for an identifier which shadow previous bdgs unless strictly necessary. In this case, it would have been better to create a new bdg with a different name, or use the lambda expression directly. fun convolve (1: t, f: t -> t, g: t -> t): t = f(1) * g(1) convolve (k: t, f: t -> t, g: t -> t): t = val f = fn (n: t) => f(n+1) f(1) * g(k) + convolve (k-1, f, g) or: fun convolve (1: t, f: t -> t, g: t -> t): t = f(1) * g(1) convolve (k: t, f: t -> t, g: t -> t): t = f(1) * g(k) + convolve (k-1, fn (n: t) => f(n+1), g) 12

1 Announcements. 2 Scan Implementation Recap. Recitation 4 Scan, Reduction, MapCollectReduce

1 Announcements. 2 Scan Implementation Recap. Recitation 4 Scan, Reduction, MapCollectReduce Recitation 4 Scan, Reduction, MapCollectReduce Parallel and Sequential Data Structures and Algorithms, 15-210 (Sprg 2013) February 6, 2013 1 Announcements How did HW 2 go? HW 3 is out get an early start!

More information

Preparing for Class: Watch le Videos! What is an ML program?

Preparing for Class: Watch le Videos! What is an ML program? Why are we here? CSE 341 : Programmg Languages Lecture 3 Local Bdgs, Options, Purity Zach Tatlock Sprg 2014 To work together to free our mds from the shackles of imperative programmg. 2 Preparg for Class:

More information

7.3.3 A Language With Nested Procedure Declarations

7.3.3 A Language With Nested Procedure Declarations 7.3. ACCESS TO NONLOCAL DATA ON THE STACK 443 7.3.3 A Language With Nested Procedure Declarations The C family of languages, and many other familiar languages do not support nested procedures, so we troduce

More information

CSci 4223 Principles of Programming Languages

CSci 4223 Principles of Programming Languages Review CSci 4223 Prciples of Programmg Languages Lecture 8 Features learned: functions, tuples, lists, let expressions, options, records, datatypes, case expressions, type synonyms, pattern matchg, exceptions

More information

Supplementary Notes on Concurrent ML

Supplementary Notes on Concurrent ML Supplementary Notes on Concurrent ML 15-312: Foundations of Programmg Languages Frank Pfenng Lecture 25 November 21, 2002 In the last lecture we discussed the π-calculus, a mimal language with synchronous

More information

A Crash Course on Standard ML

A Crash Course on Standard ML A Crash Course on Standard ML Hongwei Xi Version of November 23, 2004 1 Start Type sml-cm at a Unix wdow to get an teractive terpreter for Standard ML (SML). You can later quit the terpreter by typg ctrl-d.

More information

Recursion. Tjark Weber. Functional Programming 1. Based on notes by Sven-Olof Nyström. Tjark Weber (UU) Recursion 1 / 37

Recursion. Tjark Weber. Functional Programming 1. Based on notes by Sven-Olof Nyström. Tjark Weber (UU) Recursion 1 / 37 Tjark Weber Functional Programming 1 Based on notes by Sven-Olof Nyström Tjark Weber (UU) Recursion 1 / 37 Background FP I / Advanced FP FP I / Advanced FP This course (Functional Programming I) (5 hp,

More information

CS 312 Problem Set 1: An Introduction to SML

CS 312 Problem Set 1: An Introduction to SML CS 312 Problem Set 1: An Introduction to SML Assigned: September 1, 2003 Revised: September 4, 2003 Due: 11:59PM, September 10th, 2003 1 Introduction The goal of this problem set is to expose you to as

More information

Recursion. Lars-Henrik Eriksson. Functional Programming 1. Based on a presentation by Tjark Weber and notes by Sven-Olof Nyström

Recursion. Lars-Henrik Eriksson. Functional Programming 1. Based on a presentation by Tjark Weber and notes by Sven-Olof Nyström Lars-Henrik Eriksson Functional Programming 1 Based on a presentation by Tjark Weber and notes by Sven-Olof Nyström Tjark Weber (UU) Recursion 1 / 41 Comparison: Imperative/Functional Programming Comparison:

More information

Higher-Order Functions

Higher-Order Functions Higher-Order Functions Tjark Weber Functional Programming 1 Based on notes by Pierre Flener, Jean-Noël Monette, Sven-Olof Nyström Tjark Weber (UU) Higher-Order Functions 1 / 1 Tail Recursion http://xkcd.com/1270/

More information

Chapter 3 Programming with Recursion

Chapter 3 Programming with Recursion Plan Chapter 3 Programming with Recursion 1. Examples... 3.2 2. Correctness... 3.5 3. Construction methodology... 3.13 4. Forms of recursion... 3.16 Sven-Olof Nyström/IT Dept/Uppsala University FP 3.1

More information

CS 312, Fall Exam 1

CS 312, Fall Exam 1 Name: ID number: CS 312, Fall 2003 Exam 1 October 16, 2003 Problem 1 2 3 4 Total Grader Grade 18 24 28 30 There are 4 problems on this exam. Please check now that you have a complete exam booklet with

More information

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

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

More information

Computer Science 312 Fall Prelim 2 SOLUTIONS April 18, 2006

Computer Science 312 Fall Prelim 2 SOLUTIONS April 18, 2006 Computer Science 312 Fall 2006 Prelim 2 SOLUTIONS April 18, 2006 1 2 3 4 5 6 7 8 Total Grade /xx /xx /xx /xx /xx /xx /xx /xx /100 Grader 1 1. (xx pots) A. The bary representation of a natural number is

More information

Processadors de Llenguatge II. Functional Paradigm. Pratt A.7 Robert Harper s SML tutorial (Sec II)

Processadors de Llenguatge II. Functional Paradigm. Pratt A.7 Robert Harper s SML tutorial (Sec II) Processadors de Llenguatge II Functional Paradigm Pratt A.7 Robert Harper s SML tutorial (Sec II) Rafael Ramirez Dep Tecnologia Universitat Pompeu Fabra Paradigm Shift Imperative Paradigm State Machine

More information

CSci 4223 Principles of Programming Languages

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,

More information

Call-by-name evaluation

Call-by-name evaluation Lecture IX Keywords: call-by-value, call-by-name, and call-by-need evaluation; lazy datatypes: sequences, streams, trees; lazy evaluation; sieve of Eratosthenes; breadth-first and depth-first traversals.

More information

Version 4, 12 October 2004 Project handed out on 12 October. Complete Java implementation due on 2 November.

Version 4, 12 October 2004 Project handed out on 12 October. Complete Java implementation due on 2 November. CS 351 Programmg Paradigms, Fall 2004 1 Project 2: gnuplot Version 4, 12 October 2004 Project handed out on 12 October. Compe Java implementation due on 2 November. 2.1 The task Implement a utility for

More information

Continuation Passing Style. Continuation Passing Style

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

More information

CSE341, Fall 2011, Midterm Examination October 31, 2011

CSE341, Fall 2011, Midterm Examination October 31, 2011 CSE341, Fall 2011, Midterm Examination October 31, 2011 Please do not turn the page until the bell rings. Rules: The exam is closed-book, closed-note, except for one side of one 8.5x11in piece of paper.

More information

A quick introduction to SML

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

More information

COP-5555 PROGRAMMING LANGUAGEPRINCIPLES NOTES ON RPAL

COP-5555 PROGRAMMING LANGUAGEPRINCIPLES NOTES ON RPAL COP-5555 PROGRAMMING LANGUAGEPRINCIPLES NOTES ON 1. Introduction is a subset of PAL, the Pedagogic Algorithmic Language. There are three versions of PAL:, LPAL, and JPAL. The only one of terest here is.

More information

A Brief Introduction to Standard ML

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

More information

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

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

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

CSE3322 Programming Languages and Implementation

CSE3322 Programming Languages and Implementation Monash University School of Computer Science & Software Engineering Sample Exam 2004 CSE3322 Programming Languages and Implementation Total Time Allowed: 3 Hours 1. Reading time is of 10 minutes duration.

More information

CSCE 314 Programming Languages

CSCE 314 Programming Languages CSCE 314 Programming Languages Haskell: Higher-order Functions Dr. Hyunyoung Lee 1 Higher-order Functions A function is called higher-order if it takes a function as an argument or returns a function as

More information

CSE 341 Section 5. Winter 2018

CSE 341 Section 5. Winter 2018 CSE 341 Section 5 Winter 2018 Midterm Review! Variable Bindings, Shadowing, Let Expressions Boolean, Comparison and Arithmetic Operations Equality Types Types, Datatypes, Type synonyms Tuples, Records

More information

CSE341, Fall 2011, Midterm Examination October 31, 2011

CSE341, Fall 2011, Midterm Examination October 31, 2011 CSE341, Fall 2011, Midterm Examination October 31, 2011 Please do not turn the page until the bell rings. Rules: The exam is closed-book, closed-note, except for one side of one 8.5x11in piece of paper.

More information

Shell CSCE 314 TAMU. Higher Order Functions

Shell CSCE 314 TAMU. Higher Order Functions 1 CSCE 314: Programming Languages Dr. Dylan Shell Higher Order Functions 2 Higher-order Functions A function is called higher-order if it takes a function as an argument or returns a function as a result.

More information

CSE 341 : Programming Languages

CSE 341 : Programming Languages CSE 341 : Programming Languages Lecture 9 Lexical Scope, Closures Zach Tatlock Spring 2014 Very important concept We know function bodies can use any bindings in scope But now that functions can be passed

More information

SML A F unctional Functional Language Language Lecture 19

SML A F unctional Functional Language Language Lecture 19 SML A Functional Language Lecture 19 Introduction to SML SML is a functional programming language and acronym for Standard d Meta Language. SML has basic data objects as expressions, functions and list

More information

A Third Look At ML. Chapter Nine Modern Programming Languages, 2nd ed. 1

A Third Look At ML. Chapter Nine Modern Programming Languages, 2nd ed. 1 A Third Look At ML Chapter Nine Modern Programming Languages, 2nd ed. 1 Outline More pattern matching Function values and anonymous functions Higher-order functions and currying Predefined higher-order

More information

CIS 120 Midterm I February 16, 2015 SOLUTIONS

CIS 120 Midterm I February 16, 2015 SOLUTIONS CIS 120 Midterm I February 16, 2015 SOLUTIONS 1 1. Substitution semantics (18 points) Circle the final result of simplifying the following OCaml expressions, or Infinite loop if there is no final answer.

More information

Programming Languages

Programming Languages CSE 130 : Fall 2008 Programmg Languages Lecture 4: Variables, Environments, Scope News PA 1 due Frida 5pm PA 2 out esterda (due net Fi) Fri) Ranjit Jhala UC San Diego Variables and Bdgs Q: How to use variables

More information

Handout 2 August 25, 2008

Handout 2 August 25, 2008 CS 502: Compiling and Programming Systems Handout 2 August 25, 2008 Project The project you will implement will be a subset of Standard ML called Mini-ML. While Mini- ML shares strong syntactic and semantic

More information

Part I: Written Problems

Part I: Written Problems CSci 4223 Homework 1 DUE: Friday, February 1, 11:59 pm Instructions. Your task is to answer three written problems, and to write eleven SML functions related to calendar dates, as well as test cases for

More information

15 150: Principles of Functional Programming. Exceptions

15 150: Principles of Functional Programming. Exceptions 15 150: Principles of Functional Programming Exceptions Michael Erdmann Spring 2018 1 Topics Exceptions Referential transparency, revisited Examples to be discussed: Dealing with arithmetic errors Making

More information

Introduction to Programming in ATS

Introduction to Programming in ATS Introduction to Programmg ATS Hongwei Xi ATS Trustful Software, Inc. Copyright 2010-201? Hongwei Xi As a programmg language, ATS is both syntax-rich and feature-rich. This book troduces the reader to some

More information

Lecture Notes on Induction and Recursion

Lecture Notes on Induction and Recursion Lecture Notes on Induction and Recursion 15-317: Constructive Logic Frank Pfenning Lecture 7 September 19, 2017 1 Introduction At this point in the course we have developed a good formal understanding

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

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 Spring Today s music: Selections from the soundtrack to 2001: A Space Odyssey

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

More information

CSE341: Programming Languages Lecture 2 Functions, Pairs, Lists. Zach Tatlock Winter 2018

CSE341: Programming Languages Lecture 2 Functions, Pairs, Lists. Zach Tatlock Winter 2018 CSE341: Programming Languages Lecture 2 Functions, Pairs, Lists Zach Tatlock Winter 2018 Function definitions Functions: the most important building block in the whole course Like Java methods, have arguments

More information

Function definitions. CSE341: Programming Languages Lecture 2 Functions, Pairs, Lists. Example, extended. Some gotchas. Zach Tatlock Winter 2018

Function definitions. CSE341: Programming Languages Lecture 2 Functions, Pairs, Lists. Example, extended. Some gotchas. Zach Tatlock Winter 2018 Function definitions CSE341: Programming Languages Lecture 2 Functions, Pairs, Lists Zach Tatlock Winter 2018 Functions: the most important building block in the whole course Like Java methods, have arguments

More information

Assignment 0. Computer Science 52. Due Friday, September 7, 2018, at 5:00 pm

Assignment 0. Computer Science 52. Due Friday, September 7, 2018, at 5:00 pm Computer Science 52 Assignment 0 Due Friday, September 7, 2018, at 5:00 pm This assignment is simply to check out that you have access to and can use the SML system. It is not factored into your course

More information

15 212: Principles of Programming. Some Notes on Continuations

15 212: Principles of Programming. Some Notes on Continuations 15 212: Principles of Programming Some Notes on Continuations Michael Erdmann Spring 2011 These notes provide a brief introduction to continuations as a programming technique. Continuations have a rich

More information

What is a macro. CSE341: Programming Languages Lecture 15 Macros. Example uses. Using Racket Macros. Zach Tatlock Winter 2018

What is a macro. CSE341: Programming Languages Lecture 15 Macros. Example uses. Using Racket Macros. Zach Tatlock Winter 2018 What is a macro A macro definition describes how to transform some new syntax into different syntax in the source language CSE341: Programming Languages Lecture 15 Macros Zach Tatlock Winter 2018 A macro

More information

CSE341: Programming Languages Lecture 15 Macros. Zach Tatlock Winter 2018

CSE341: Programming Languages Lecture 15 Macros. Zach Tatlock Winter 2018 CSE341: Programming Languages Lecture 15 Macros Zach Tatlock Winter 2018 What is a macro A macro definition describes how to transform some new syntax into different syntax in the source language A macro

More information

Programming Languages and Techniques (CIS120)

Programming Languages and Techniques (CIS120) Programming Languages and Techniques (CIS120) Lecture 3 September 5, 2018 Value-Oriented Programming (continued) Lists and Recursion CIS 120 Announcements Homework 1: OCaml Finger Exercises Due: Tuesday

More information

Introduction to SML Basic Types, Tuples, Lists, Trees and Higher-Order Functions

Introduction to SML Basic Types, Tuples, Lists, Trees and Higher-Order Functions Introduction to SML Basic Types, Tuples, Lists, Trees and Higher-Order Functions Michael R. Hansen mrh@imm.dtu.dk Informatics and Mathematical Modelling Technical University of Denmark c Michael R. Hansen,

More information

The type checker will complain that the two branches have different types, one is string and the other is int

The type checker will complain that the two branches have different types, one is string and the other is int 1 Intro to ML 1.1 Basic types Need ; after expression - 42 = ; val it = 42 : int - 7+1; val it = 8 : int Can reference it - it+2; val it = 10 : int - if it > 100 then "big" else "small"; val it = "small"

More information

Programming Paradigms Languages F28PL, Lecture 1

Programming Paradigms Languages F28PL, Lecture 1 Programming Paradigms Languages F28PL, Lecture 1 Jamie Gabbay October 14, 2016 1 / 37 About me My name is Murdoch James Gabbay everybody calls me Jamie. I got a PhD in Cambridge in 2001. Since then I have

More information

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

More information

Homework 5. Notes. Turn-In Instructions. Reading. Problems. Handout 19 CSCI 334: Spring (Required) Read Mitchell, Chapters 6 and 7.

Homework 5. Notes. Turn-In Instructions. Reading. Problems. Handout 19 CSCI 334: Spring (Required) Read Mitchell, Chapters 6 and 7. Homework 5 Due Wednesday, 14 March Handout 19 CSCI 334: Spring 2018 Notes This homework has two types of problems: Problems: You will turn in answers to these questions. Pair Programming: This part involves

More information

Exercise 1 ( = 24 points)

Exercise 1 ( = 24 points) 1 Exercise 1 (4 + 5 + 4 + 6 + 5 = 24 points) The following data structure represents polymorphic binary trees that contain values only in special Value nodes that have a single successor: data Tree a =

More information

Contextual Analysis (2) Limitations of CFGs (3)

Contextual Analysis (2) Limitations of CFGs (3) G53CMP: Lecture 5 Contextual Analysis: Scope I Henrik Nilsson University of Nottgham, UK This Lecture Limitations of context-free languages: Why checkg contextual constrats is different from checkg syntactical

More information

Functional Programming Mid-term exam Tuesday 3/10/2017

Functional Programming Mid-term exam Tuesday 3/10/2017 Functional Programming Mid-term exam Tuesday 3/10/2017 Name: Student number: Before you begin: Do not forget to write down your name and student number above. If necessary, explain your answers in English.

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

CSCC24 Functional Programming Typing, Scope, Exceptions ML

CSCC24 Functional Programming Typing, Scope, Exceptions ML CSCC24 Functional Programming Typing, Scope, Exceptions ML Carolyn MacLeod 1 winter 2012 1 Based on slides by Anya Tafliovich, with many thanks to Gerald Penn and Sheila McIlraith. motivation Consider

More information

UNIVERSITY OF TORONTO Faculty of Arts and Science. Midterm Sample Solutions CSC324H1 Duration: 50 minutes Instructor(s): David Liu.

UNIVERSITY OF TORONTO Faculty of Arts and Science. Midterm Sample Solutions CSC324H1 Duration: 50 minutes Instructor(s): David Liu. UNIVERSITY OF TORONTO Faculty of Arts and Science Midterm Sample s CSC324H1 Duration: 50 minutes Instructor(s): David Liu. No Aids Allowed Name: Student Number: Please read the following guidelines carefully.

More information

SML Style Guide. Last Revised: 31st August 2011

SML Style Guide. Last Revised: 31st August 2011 SML Style Guide Last Revised: 31st August 2011 It is an old observation that the best writers sometimes disregard the rules of rhetoric. When they do so, however, the reader will usually find in the sentence

More information

Australian researchers develop typeface they say can boost memory, that could help students cramming for exams.

Australian researchers develop typeface they say can boost memory, that could help students cramming for exams. Font of all knowledge? Australian researchers develop typeface they say can boost memory, that could help students cramming for exams. About 400 university students took part in a study that found a small

More information

CMSC 330, Fall 2013, Practice Problems 3

CMSC 330, Fall 2013, Practice Problems 3 CMSC 330, Fall 2013, Practice Problems 3 1. OCaml and Functional Programming a. Define functional programming b. Define imperative programming c. Define higher-order functions d. Describe the relationship

More information

type environment updated subtype sound

type environment updated subtype sound #1 Type Checkg #2 One-Slide Summary A type environment gives types for free variables. You typecheck a let-body with an environment that has been updated to conta the new let-variable. If an object of

More information

Lecture 5: Lazy Evaluation and Infinite Data Structures

Lecture 5: Lazy Evaluation and Infinite Data Structures Lecture 5: Lazy Evaluation and Infinite Data Structures Søren Haagerup Department of Mathematics and Computer Science University of Southern Denmark, Odense October 3, 2017 How does Haskell evaluate a

More information

CSE341 Autumn 2017, Midterm Examination October 30, 2017

CSE341 Autumn 2017, Midterm Examination October 30, 2017 CSE341 Autumn 2017, Midterm Examination October 30, 2017 Please do not turn the page until 2:30. Rules: The exam is closed-book, closed-note, etc. except for one side of one 8.5x11in piece of paper. Please

More information

F28PL1 Programming Languages. Lecture 12: Standard ML 2

F28PL1 Programming Languages. Lecture 12: Standard ML 2 F28PL1 Programming Languages Lecture 12: Standard ML 2 Declaration introduce a variable associate identifier with value - val identifier = expression; > val identifier = value : type identifier - any sequence

More information

Exercise 1 ( = 18 points)

Exercise 1 ( = 18 points) 1 Exercise 1 (4 + 5 + 4 + 5 = 18 points) The following data structure represents polymorphic binary trees that contain values only in special Value nodes that have a single successor: data Tree a = Leaf

More information

ormap, andmap, and filter

ormap, andmap, and filter ormap, andmap, and filter CS 5010 Program Design Paradigms Bootcamp Lesson 6.3 Mitchell Wand, 2012-2015 This work is licensed under a Creative Commons Attribution-NonCommercial 4.0 International License.

More information

G Programming Languages - Fall 2012

G Programming Languages - Fall 2012 G22.2110-003 Programming Languages - Fall 2012 Lecture 3 Thomas Wies New York University Review Last week Names and Bindings Lifetimes and Allocation Garbage Collection Scope Outline Control Flow Sequencing

More information

CSc 520. Gofer III. Accumulative Recursion. Accumulative Recursion... Stack Recursion. Principles of Programming Languages. Christian Collberg

CSc 520. Gofer III. Accumulative Recursion. Accumulative Recursion... Stack Recursion. Principles of Programming Languages. Christian Collberg Slide 7 2 Accumulative Recursion We can sometimes get a more efficient solution by giving the function one extra argument, the accumulator, which is used to gather the final result. We will need to use

More information

CSE 341: Programming Languages

CSE 341: Programming Languages CSE 341: Programming Languages Autumn 2005 Lecture 10 Mutual Recursion, Equivalence, and Syntactic Sugar CSE 341 Autumn 2005, Lecture 10 1 Mutual Recursion You ve already seen how multiple functions can

More information

ML Built-in Functions

ML Built-in Functions ML Built-in Functions Since ML is a functional programming language, many of its built-in functions are concerned with function application to objects and structures. In ML, built-in functions are curried

More information

Tentamen Functioneel Programmeren 2001 Informatica, Universiteit Utrecht Docent: Wishnu Prasetya

Tentamen Functioneel Programmeren 2001 Informatica, Universiteit Utrecht Docent: Wishnu Prasetya Tentamen Functioneel Programmeren 2001 Informatica, Universiteit Utrecht Docent: Wishnu Prasetya 04-05-2001, 09.00-12.00, Educatorium Gamma This test consists of two parts. For the first part, which is

More information

Homework 1. Notes. What To Turn In. Unix Accounts. Reading. Handout 3 CSCI 334: Spring, 2017

Homework 1. Notes. What To Turn In. Unix Accounts. Reading. Handout 3 CSCI 334: Spring, 2017 Homework 1 Due 14 February Handout 3 CSCI 334: Spring, 2017 Notes This homework has three types of problems: Self Check: You are strongly encouraged to think about and work through these questions, but

More information

Introduction to SML Getting Started

Introduction to SML Getting Started Introduction to SML Getting Started Michael R. Hansen mrh@imm.dtu.dk Informatics and Mathematical Modelling Technical University of Denmark c Michael R. Hansen, Fall 2004 p.1/15 Background Standard Meta

More information

CSC/MAT-220: Lab 6. Due: 11/26/2018

CSC/MAT-220: Lab 6. Due: 11/26/2018 CSC/MAT-220: Lab 6 Due: 11/26/2018 In Lab 2 we discussed value and type bindings. Recall, value bindings bind a value to a variable and are intended to be static for the life of a program. Type bindings

More information

Inductive Data Types

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

More information

Factorial. Next. Factorial. How does it execute? Tail recursion. How does it execute? More on recursion. Higher-order functions

Factorial. Next. Factorial. How does it execute? Tail recursion. How does it execute? More on recursion. Higher-order functions Next More on recursion Higher-order functions takg and returng functions Factorial let rec fact n = Along the way, will see map and fold 1 2 Factorial let rec fact n = if n

More information

CS1 Recitation. Week 2

CS1 Recitation. Week 2 CS1 Recitation Week 2 Sum of Squares Write a function that takes an integer n n must be at least 0 Function returns the sum of the square of each value between 0 and n, inclusive Code: (define (square

More information

02157 Functional Programming Lecture 1: Introduction and Getting Started

02157 Functional Programming Lecture 1: Introduction and Getting Started Lecture 1: Introduction and Getting Started nsen 1 DTU Informatics, Technical University of Denmark Lecture 1: Introduction and Getting Started MRH 6/09/2012 WELCOME to Teacher: nsen DTU Informatics, mrh@imm.dtu.dk

More information

Lecture 15 CIS 341: COMPILERS

Lecture 15 CIS 341: COMPILERS Lecture 15 CIS 341: COMPILERS Announcements HW4: OAT v. 1.0 Parsing & basic code generation Due: March 28 th No lecture on Thursday, March 22 Dr. Z will be away Zdancewic CIS 341: Compilers 2 Adding Integers

More information

CSE341: Programming Languages Lecture 7 First-Class Functions. Dan Grossman Winter 2013

CSE341: Programming Languages Lecture 7 First-Class Functions. Dan Grossman Winter 2013 CSE341: Programming Languages Lecture 7 First-Class Functions Dan Grossman Winter 2013 What is functional programming? Functional programming can mean a few different things: 1. Avoiding mutation in most/all

More information

15-451/651: Design & Analysis of Algorithms November 20, 2018 Lecture #23: Closest Pairs last changed: November 13, 2018

15-451/651: Design & Analysis of Algorithms November 20, 2018 Lecture #23: Closest Pairs last changed: November 13, 2018 15-451/651: Design & Analysis of Algorithms November 20, 2018 Lecture #23: Closest Pairs last changed: November 13, 2018 1 Prelimaries We ll give two algorithms for the followg closest pair problem: Given

More information

CSE341 Spring 2016, Final Examination June 6, 2016

CSE341 Spring 2016, Final Examination June 6, 2016 CSE341 Spring 2016, Final Examination June 6, 2016 Please do not turn the page until 8:30. Rules: The exam is closed-book, closed-note, etc. except for both sides of one 8.5x11in piece of paper. Please

More information

15 150: Principles of Functional Programming. More about Higher-Order Functions

15 150: Principles of Functional Programming. More about Higher-Order Functions 15 150: Principles of Functional Programming More about Higher-Order Functions Michael Erdmann Spring 2018 1 Topics Currying and uncurrying Staging computation Partial evaluation Combinators 2 Currying

More information

Next. Tail Recursion: Factorial. How does it execute? Tail recursion. Tail recursive factorial. Tail recursive factorial.

Next. Tail Recursion: Factorial. How does it execute? Tail recursion. Tail recursive factorial. Tail recursive factorial. Next Tail Recursion: Factorial More on recursion Higher-order functions takg and returng functions Along the way, will see map and fold let rec fact n = if n

More information

(ii) Define a function ulh that takes a list xs, and pairs each element with all other elements in xs.

(ii) Define a function ulh that takes a list xs, and pairs each element with all other elements in xs. EXAM FUNCTIONAL PROGRAMMING Tuesday the 1st of October 2016, 08.30 h. - 10.30 h. Name: Student number: Before you begin: Do not forget to write down your name and student number above. If necessary, explain

More information

Programming Languages

Programming Languages CSE 130 : Winter 2013 Programming Languages Lecture 3: Crash Course, Datatypes Ranjit Jhala UC San Diego 1 Story So Far... Simple Expressions Branches Let-Bindings... Today: Finish Crash Course Datatypes

More information

Fall 2018 Stephen Brookes. LECTURE 2 Thursday, August 30

Fall 2018 Stephen Brookes. LECTURE 2 Thursday, August 30 15-150 Fall 2018 Stephen Brookes LECTURE 2 Thursday, August 30 Announcements HOMEWORK 1 is out Read course policy Must be your OWN work Integrity No collaboration (only limited discussion) Rules will be

More information

Higher Order Functions in Haskell

Higher Order Functions in Haskell Higher Order Functions in Haskell Evan Misshula 2018-09-10 Outline Curried Functions Curried comparison Example partial application partial application of a string function Returned functions ZipWith flip

More information

Functional programming Primer I

Functional programming Primer I Functional programming Primer I COS 320 Compiling Techniques Princeton University Spring 2016 Lennart Beringer 1 Characteristics of functional programming Primary notions: functions and expressions (not

More information

Recap from last time. Programming Languages. CSE 130 : Fall Lecture 3: Data Types. Put it together: a filter function

Recap from last time. Programming Languages. CSE 130 : Fall Lecture 3: Data Types. Put it together: a filter function CSE 130 : Fall 2011 Recap from last time Programming Languages Lecture 3: Data Types Ranjit Jhala UC San Diego 1 2 A shorthand for function binding Put it together: a filter function # let neg = fun f

More information

FUNCTIONAL PROGRAMMING

FUNCTIONAL PROGRAMMING FUNCTIONAL PROGRAMMING Map, Fold, and MapReduce Prof. Clarkson Summer 2015 Today s music: Selections from the soundtrack to 2001: A Space Odyssey Review Yesterday: Lists: OCaml's awesome built-in datatype

More information

The Haskell HOP: Higher-order Programming

The Haskell HOP: Higher-order Programming The Haskell HOP: Higher-order Programming COS 441 Slides 6 Slide content credits: Ranjit Jhala, UCSD Agenda Haskell so far: First-order functions This time: Higher-order functions: Functions as data, arguments

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

THAT ABOUT WRAPS IT UP Using FIX to Handle Errors Without Exceptions, and Other Programming Tricks

THAT ABOUT WRAPS IT UP Using FIX to Handle Errors Without Exceptions, and Other Programming Tricks THAT ABOUT WRAPS IT UP Usg FIX to Handle Errors Without Exceptions, and Other Programmg Tricks BRUCE J. MCADAM Technical Report ECS LFCS 97 375 Department of Computer Science University of Edburgh November

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 Fall 2017 1 So Far, Only Functional Programming We haven t given you any way so far to change something in memory All

More information

Sample Exam; Solutions

Sample Exam; Solutions Sample Exam; Solutions Michael P. Fourman February 2, 2010 1 Introduction This document contains solutions to the sample questions given in Lecture Note 10 Short Question 5 marks Give the responses of

More information