CS457/557 Functional Languages

Similar documents
CS 11 Haskell track: lecture 1

CSCE 314 TAMU Fall CSCE 314: Programming Languages Dr. Flemming Andersen. Haskell Basics

CSCE 314 Programming Languages

Programming Paradigms and Languages Introduction to Haskell. dr Robert Kowalczyk WMiI UŁ

PROGRAMMING IN HASKELL. Chapter 2 - First Steps

PL Categories: Functional PLs Introduction to Haskell Haskell: Functions

CSE341: Programming Languages Lecture 26 Course Victory Lap. Dan Grossman Spring 2016

Advanced Topics in Programming Languages Lecture 2 - Introduction to Haskell

Lecture 8: Summary of Haskell course + Type Level Programming

Introduction to Prof. Clarkson Fall Today s music: Prelude from Final Fantasy VII by Nobuo Uematsu (remastered by Sean Schafianski)

Lecture 1 August 9, 2017

About the Tutorial. Audience. Prerequisites. Copyright & Disclaimer. Haskell Programming

COSE212: Programming Languages. Lecture 0 Course Overview

Side Effects (3A) Young Won Lim 1/13/18

FUNCTIONAL PROGRAMMING 1 HASKELL BASICS

Chapter 11 :: Functional Languages

Welcome to CS 135 (Winter 2018)

Introduction to Prof. Clarkson Fall Today s music: Prelude from Final Fantasy VII by Nobuo Uematsu (remastered by Sean Schafianski)

n n Try tutorial on front page to get started! n spring13/ n Stack Overflow!

Introduction to Haskell

Introduction to Prof. Clarkson Fall Today s music: Prelude from Final Fantasy VII by Nobuo Uematsu (remastered by Sean Schafianski)

Introduction to Nate Foster Spring 2018

Functional Languages. Hwansoo Han

Introduction. chapter Functions

Programming Paradigms

LECTURE 16. Functional Programming

COP4020 Programming Languages. Functional Programming Prof. Robert van Engelen

Welcome to CS 135 (Fall 2018) Themes of the course. Lectures. cs135/

Recursion and Induction: Haskell; Primitive Data Types; Writing Function Definitions

CS558 Programming Languages

PROGRAMMING IN HASKELL. Chapter 2 - First Steps

CS558 Programming Languages

Functional Programming Lecture 1: Introduction

Functional Programming. Big Picture. Design of Programming Languages

Quick announcement. Midterm date is Wednesday Oct 24, 11-12pm.

CS 360: Programming Languages Lecture 10: Introduction to Haskell

CSCI-GA Scripting Languages

CS558 Programming Languages

Scheme: Expressions & Procedures

Introduction to Programming, Aug-Dec 2008

CSc 372. Comparative Programming Languages. 2 : Functional Programming. Department of Computer Science University of Arizona

Programming Languages and Techniques (CIS120)

CS 4349 Lecture August 21st, 2017

CPL 2016, week 10. Clojure functional core. Oleg Batrashev. April 11, Institute of Computer Science, Tartu, Estonia

CSE413: Programming Languages and Implementation Racket structs Implementing languages with interpreters Implementing closures

PROGRAMMING IN HASKELL. Chapter 2 - First Steps

COSE212: Programming Languages. Lecture 3 Functional Programming in OCaml

Spring 2003 Instructor: Dr. Shahadat Hossain. Administrative Matters Course Information Introduction to Programming Techniques

CS558 Programming Languages

San José State University Department of Computer Science CS-144, Advanced C++ Programming, Section 1, Spring 2018

Languages and Compilers

Functional Programming Languages (FPL)

Advances in Programming Languages

Functional Programming Principles in Scala. Martin Odersky

Haskell 101. (Version 1 (July 18, 2012)) Juan Pedro Villa Isaza

Practical Haskell. An introduction to functional programming. July 21, Practical Haskell. Juan Pedro Villa-Isaza. Introduction.

CIS 194: Homework 3. Due Wednesday, February 11, Interpreters. Meet SImPL

Side Effects (3B) Young Won Lim 11/23/17

Computer Science 210: Data Structures

Side Effects (3B) Young Won Lim 11/20/17

Software System Design and Implementation

Functional Programming

Haskell Scripts. Yan Huang

CS 241 Data Organization. August 21, 2018

Lecture 5: Lazy Evaluation and Infinite Data Structures

Welcome to. Instructor Marc Pomplun CS 470/670. Introduction to Artificial Intelligence 1/26/2016. Spring Selectivity in Complex Scenes

Side Effects (3B) Young Won Lim 11/27/17

Programming Languages and Techniques (CIS120)

CSC116: Introduction to Computing - Java

Haskell: Lists. CS F331 Programming Languages CSCE A331 Programming Language Concepts Lecture Slides Friday, February 24, Glenn G.

Outline. Logistics. Logistics. Principles of Software (CSCI 2600) Spring Logistics csci2600/

CSCI 136 Data Structures & Advanced Programming. Fall 2018 Instructors Bill Lenhart & Bill Jannen

Functional Programming for Logicians - Lecture 1

The Haskell HOP: Higher-order Programming

Who are we? Andre Platzer Out of town the first week GHC TAs Alex Crichton, senior in CS and ECE Ian Gillis, senior in CS

Functional Programming in Haskell for A level teachers

Object-Oriented Programming for Managers

JVM ByteCode Interpreter

An introduction to functional programming. July 23, 2010

First Haskell Exercises

Functional Programming

Key components of a lang. Deconstructing OCaml. In OCaml. Units of computation. In Java/Python. In OCaml. Units of computation.

Principles of Programming Languages 2017W, Functional Programming

CS1 Lecture 3 Jan. 22, 2018

3. Functional Programming. Oscar Nierstrasz

CS 3813/718 Fall Python Programming. Professor Liang Huang.

CSCC24 Functional Programming Scheme Part 2

Computer Science II Lecture 1 Introduction and Background

About the Tutorial. Audience. Prerequisites. Copyright & Disclaimer. Haskell Programming

Course Syllabus. Programming Language Paradigms. Spring - DIS Copenhagen. Semester & Location: Elective Course - 3 credits.

CS 440: Programming Languages and Translators, Spring 2019 Mon

CS 3110 Lecture 1 Course Overview

CS 3360 Design and Implementation of Programming Languages. Exam 1

Software System Design and Implementation

Announcements. 1. Forms to return today after class:

Programming Languages and Compilers (CS 421)

Introduction to Functional Programming and Haskell. Aden Seaman

Programming Languages

Introduction to Prof. Clarkson Fall Today s music: Prelude from Final Fantasy VII by Nobuo Uematsu (remastered by Sean Schafianski)

Programming Languages and Techniques (CIS120)

Transcription:

CS457/557 Functional Languages Spring 2018 Lecture 1: Course Introduction Andrew Tolmach Portland State University (with thanks to Mark P. Jones) 1

Goals of this course Introduce the beautiful ideas of functional programming Explain new strategies for building and verifying programs Demonstrate that functional programming has realworld utility 2

Important Underlying Themes Computing by calculating Recursive algorithms and types Type-driven programming Abstraction over values, functions, types Programming by composition Reasoning about programs 3

Specific Topics (subject to revision) Haskell programming language Programming with lists Programming with algebraic data types Polymorphism and type classes Higher-order functions 4

More specific topics (subject to revision) Functions as data Monads Laziness Parallelism Implementation 5

What this course is not An advanced course in the details of Haskell (and its many non-standard extensions) A detailed tour of the Haskell library A comparative study of functional languages A good course to take if you don t really like programming much 6

What should you bring? Your brain, prepared by these prerequisites CS 202,311 are formally required (for 457) CS320 is useful, but not essential Good background in programming (but not FP) Your well-charged laptop! This is a hands-on course, and we will be doing lab work towards the end of each class meeting 7

Administrivia Instructor: Andrew Tolmach Office hours: Tu 1-2pm or by appointment TA: Chris Chak Office hours: M 4-5 (tentative) Course web page www.cs.pdx.edu/~apt/cs457 For all homework assignments, lectures notes, etc. Course mailing list cs457list@cs.pdx.edu For helpful announcements and for you to ask questions Course homework submission address cs457acc@pdx.edu For homework submission only! Don t get the two mailing lists confused! 8

Course format Meet Mon/Wed 2-3:50pm Start each class with lecture Finish with problem-solving lab (bring your laptop!) Weekly homeworks due Wednesdays Essential part of course 55% of grade In-class midterm on May 7 20% of grade Final programming project due June 6 25% of grade Can be done individually or in a team of 2 NO final exam 9

Policies By default, late work is not accepted Contact us if you feel an extension is justified Work individually on the homeworks Discussion is good But anything you turn should be your own, individual work Don t cheat! 10

g Reading Syllabus Resources Material Textbook Textbook Lecture slides Notes on Haskell Huge amount of on-line Slides, etc. material, starting at Plenty of additional www.haskell.org/documentation reading material is online But available beware of unnecessary complexity! Beware of unnecessary complexity! 20 11

What is Functional Programming? A style of programming that emphasizes evaluation of expressions, rather than execution of commands Expressions are formed by using functions to combine basic values Functions are first-class values They can be stored in data structures They can be passed as arguments or returned as results of other functions A functional language is one that supports and encourages programming in a functional style 12

Pure Functional Programming No mutation! Everything (variables, data structures, ) is immutable Expressions have no side-effects, like updates to global variables or output to the screen Function results depend only on input values Deterministic, like functions in mathematics Makes programs much more compositional Refactoring and parallelizing are much easier 13

The functional language landscape Impure, strict evaluation, dynamic typing: Lisp, Scheme, Racket, Erlang, Clojure, Impure, strict evaluation, static typing: Standard ML (SML), OCaml, F#, Scala, Pure, lazy evaluation, static typing: Haskell, Miranda, Orwell, Other combinations relatively unexplored 14

Haskell By far the most important pure, lazy FL Developed by committee of academics in late 80 s Combined and standardized several earlier languages Current stable version is Haskell 2010 Dominant implementation is Glasgow Haskell (ghc) Includes many experimental extensions (which we will mostly avoid) 15

Write a program to add up the numbers from 1 to 10. 16

In C, C++, Java, C#, initialization initialization int tot = 0; for (int i=1; i<11; i++) tot = tot + i; update iteration update implicit result returns in the variable tot 17

In OCaml accumulating parameter let rec sum i tot = if i > 10 then tot else sum (i+1) (tot+i) in sum 1 0 initialization (tail) recursion result is the value of the expression 18

In Haskell sum [1..10] combining function the list of numbers to add result is the value of the expression 19

Was that too simple? Tried to give idiomatic solutions in each language This example makes Haskell look good, partly because sum function is already in standard library An objective comparison between languages should account for library code as well as main program Here s an alternative solution using somewhat less specialized library functions foldr (+) 0 [1..10] 20

We can write OCaml in Haskell let sum i tot i > 10 = tot otherwise = sum (i+1) (tot+1) in sum 1 0 and sometimes we will need to write explicit recursions like this but we will try to avoid them when we can 21

we almost never need to do this! We can write C in Haskell! X loop totval <- readioref tot print totval result is printed by main program import Data.IORef main = do tot <- newioref 0 i <- newioref 1 let loop = do ival <- readioref i if ival < 11 then do modifyioref tot (+ival) modifyioref i (+1) loop else return () 22

What makes a good program? Correctness Maintainability (Clarity, Conciseness, Modularity, ) Performance 23

Raising the level of abstraction If you want to reduce [design time], you have to stop thinking about something you used to have to think about (Joe Stoy, quoted on the Haskell mailing list) Example: memory allocation and deallocation Example: data representation Example: order of evaluation Example: (restrictive) type specifications 24

Computing by Calculating In high school algebra, we learn to rearrange and simplify numeric expressions to obtain answers Pocket calculators automate details of calculation In pure functional programming, we can work with program expressions in much the same way With multiple primitive data types, lists, functions, userdefined types Ability to name (abstract over) values and operations Functional language evaluators automate calculation 25

Example calculation In pure functional language, we can perform computations by replacing defined symbols with their definitions Given a = 10 b = 7 diff x y = if x <= y then y-x else x-y Can calculate diff a b if a <= b then b-a else a-b if 10 <= 7 then 7-10 else 10-7 if False then 7-10 else 10-7 10-7 3 26

Haskell Pragmatics Glasgow Haskell ecosystem ghc native code compiler ghci interpreter hackage package database cabal, stack package managers Haskell Platform convenient single download Other implementations exists (Hugs, ) 27

Starting ghci user$ ghci GHCi, version 8.2.2: http://www.haskell.org/ghc/ :? for help Prelude> The most important commands: :q quit :l file load file :e file edit file expr The REPL (read-eval-print loop): 1. Enter expression at prompt 2. Hit return evaluate expression 3. Expression is read, checked, and evaluated 4. Result (or error) is displayed 5. Repeat from step 1 28

Simple expressions The usual arithmetic operations 1 + 2 * 3 (1 + 2) * 3 Comparisons 1 == 2 a < z Boolean operators True && False not False Standard library functions on numbers odd 2 odd (2+1) sqrt 4.0 + 2.0 sqrt (4.0 + 2.0) Lists and library functions on them [1,2,3] length [True,True,False] sum [1..10] 29

Expressions have Types The type of an expression tells you what kind of value the expression evaluates to In Haskell, read :: as has type Examples: 1 :: Int a ::Char True :: Bool 1.2 :: Float You can ask ghci to tell you the type of an expression by entering :t expr 30

Type Errors in ghci Prelude> 'a' && True <interactive>:7:1: error: Couldn't match expected type Bool with actual type Char In the first argument of (&&), namely 'a' In the expression: 'a' && True In an equation for it : it = 'a' && True Prelude> odd 1 + 2 <interactive>:8:1: error: No instance for (Num Bool) arising from a use of + In the expression: odd 1 + 2 In an equation for it : it = odd 1 + 2 31

Definitions and Scripts So far, have just been evaluating expressions What if we want to Define a new constant (i.e. give a name to the result of an expression)? Define a new function? Define a type? We place definitions in a script file with a.hs suffix that can be loaded into ghci 32

Simple Script Place the following test in a file defs.hs square x = x * x fact n = product [1..n] diff x y = if x <= y then y-x else x-y a = 10 33

Simple Script Pass the filename as a command line argument to ghci, or use the :l command from inside ghci user$ ghci GHCi, version 8.2.2: http://www.haskell.org/ghc/ :? for help Prelude> :l defs.hs [1 of 1] Compiling Main ( defs.hs, interpreted ) Ok, one module loaded. *Main> square 12 144 *Main> fact 32 263130836933693530167218012160000000 *Main> diff 1 a 9 *Main> diff a 1 9 *Main> 34

Let s get things running Get to a position where you can run ghci, by either installing it on your machine; or starting a remote shell on linuxlab.cs.pdx.edu Download this file from the course web page: http://www.cs.pdx.edu/~apt/cs457/hw0.hs Start ghci, load hw0.hs, and evaluate the following expression: idme your-name-here envvar where the first string is your name and the second string is the name of the shell environment variable containing your username, i.e. USER on *nix and username on Windows This should produce an output file in your current directory called my_identity.txt Send mail to the homework account cs457acc@pdx.edu with my_identity.txt as an attached file 35