CS5205Haskell1 CS5205: Foundations in Programming Languages Overview Lecturer : Chin Wei Ngan Office : S15 06-01 “Language.

Slides:



Advertisements
Similar presentations
Introduction to Compilation of Functional Languages Wanhe Zhang Computing and Software Department McMaster University 16 th, March, 2004.
Advertisements

ML Datatypes.1 Standard ML Data types. ML Datatypes.2 Concrete Datatypes  The datatype declaration creates new types  These are concrete data types,
Getting started with ML ML is a functional programming language. ML is statically typed: The types of literals, values, expressions and functions in a.
Functional Programming. Pure Functional Programming Computation is largely performed by applying functions to values. The value of an expression depends.
ML: a quasi-functional language with strong typing Conventional syntax: - val x = 5; (*user input *) val x = 5: int (*system response*) - fun len lis =
C H A P T E R E I G H T Even More Functional Programming Programming Languages – Principles and Paradigms by Allen Tucker, Robert Noonan.
Functional Design and Programming Lecture 1: Functional modeling, design and programming.
0 PROGRAMMING IN HASKELL Chapter 4 - Defining Functions.
Semantics with Applications Mooly Sagiv Schrirber html:// Textbooks:Winskel The.
CS5205: Foundation in Programming Languages Lecture 1 : Overview
Type Inference: CIS Seminar, 11/3/2009 Type inference: Inside the Type Checker. A presentation by: Daniel Tuck.
Cse536 Functional Programming 1 7/14/2015 Lecture #2, Sept 29, 2004 Reading Assignments –Begin Chapter 2 of the Text Home work #1 can be found on the webpage,
1 COMP 144 Programming Language Concepts Felix Hernandez-Campos Lecture 19: Functions, Types and Data Structures in Haskell COMP 144 Programming Language.
CSE341: Programming Languages Lecture 11 Type Inference Dan Grossman Winter 2013.
PPL Syntax & Formal Semantics Lecture Notes: Chapter 2.
PPL Syntax & Formal Semantics Lecture Notes: Chapter 2.
CS 2104 : Prog. Lang. Concepts. Functional Programming I Lecturer : Dr. Abhik Roychoudhury School of Computing From Dr. Khoo Siau Cheng’s lecture notes.
0 PROGRAMMING IN HASKELL Typeclasses and higher order functions Based on lecture notes by Graham Hutton The book “Learn You a Haskell for Great Good” (and.
Functional Programming in Haskell Motivation through Concrete Examples Adapted from Lectures by Simon Thompson.
PrasadCS7761 Haskell Data Types/ADT/Modules Type/Class Hierarchy Lazy Functional Language.
ML Datatypes.1 Standard ML Data types. ML Datatypes.2 Concrete Datatypes  The datatype declaration creates new types  These are concrete data types,
0 REVIEW OF HASKELL A lightening tour in 45 minutes.
0 PROGRAMMING IN HASKELL Chapter 7 - Defining Functions, List Comprehensions.
Advanced Functional Programming 2009 Ulf Norell (lecture by Jean-Philippe Bernardy)
Sound Haskell Dana N. Xu University of Cambridge Joint work with Simon Peyton Jones Microsoft Research Cambridge Koen Claessen Chalmers University of Technology.
Functional Programming With examples in F#. Pure Functional Programming Functional programming involves evaluating expressions rather than executing commands.
1-Nov-15 Haskell II Functions and patterns. Data Types Int + - * / ^ even odd Float + - * / ^ sin cos pi truncate Char ord chr isSpace isUpper … Bool.
1 Functional Programming Lecture 6 - Algebraic Data Types.
A Second Look At ML 1. Outline Patterns Local variable definitions A sorting example 2.
Overview of the Haskell 98 Programming Language
CS5205Haskell1 CS5205: Foundations in Programming Languages FP with Haskell A pure lazy functional language that embodies many innovative ideas in language.
CS 2104 – Prog. Lang. Concepts Functional Programming II Lecturer : Dr. Abhik Roychoudhury School of Computing From Dr. Khoo Siau Cheng’s lecture notes.
1 Haskell Kevin Atkinson John Simmons. 2 Contents Introduction Type System Variables Functions Module System I/O Conclusions.
CS5205Introduction1 CS5205: Foundation in Programming Languages Lecture 0 : Overview Lecturer : Chin Wei Ngan Office : COM2.
Com Functional Programming Lazy Evaluation Marian Gheorghe Lecture 13 Module homepage Mole & ©University of Sheffieldcom2010.
1 CS 457/557: Functional Languages Lists and Algebraic Datatypes Mark P Jones Portland State University.
1 Compiler Construction (CS-636) Muhammad Bilal Bashir UIIT, Rawalpindi.
Error Example - 65/4; ! Toplevel input: ! 65/4; ! ^^ ! Type clash: expression of type ! int ! cannot have type ! real.
Lee CSCE 314 TAMU 1 CSCE 314 Programming Languages Haskell: More on Functions and List Comprehensions Dr. Hyunyoung Lee.
Chapter SevenModern Programming Languages1 A Second Look At ML.
Advanced Functional Programming Tim Sheard 1 Lecture 17 Advanced Functional Programming Tim Sheard Oregon Graduate Institute of Science & Technology Lecture:
1 Static Contract Checking for Haskell Dana N. Xu University of Cambridge Joint work with Simon Peyton Jones Microsoft Research Cambridge Koen Claessen.
0 PROGRAMMING IN HASKELL Based on lecture notes by Graham Hutton The book “Learn You a Haskell for Great Good” (and a few other sources) Odds and Ends,
CMSC 330: Organization of Programming Languages Operational Semantics.
Functional Programming Lecture 3 - Lists Muffy Calder.
Haskell Chapter 5, Part II. Topics  Review/More Higher Order Functions  Lambda functions  Folds.
CSE 341 : Programming Languages Lecture 9 Lexical Scope, Closures Zach Tatlock Spring 2014.
An introduction to functional programming using Haskell CENG242 –Recitation 1.
Miranda Programming Language By Bindu H. Vinay. History of Miranda  Miranda was developed in by David Turner  It is currently being marketed.
6-Jul-16 Haskell II Functions and patterns. Data Types Int + - * / ^ even odd Float + - * / ^ sin cos pi truncate Char ord chr isSpace isUpper … Bool.
Advanced Functional Programming 2010
CS314 – Section 5 Recitation 9
Set Comprehensions In mathematics, the comprehension notation can be used to construct new sets from old sets. {x2 | x  {1...5}} The set {1,4,9,16,25}
Set Comprehensions In mathematics, the comprehension notation can be used to construct new sets from old sets. {x2 | x  {1...5}} The set {1,4,9,16,25}
Functional Programming
Functional Programming
Principles of programming languages 12: Functional programming
Types CSCE 314 Spring 2016.
ML: a quasi-functional language with strong typing
Theory of Computation Lecture 4: Programs and Computable Functions II
Functions and patterns
A lightening tour in 45 minutes
Closures and Streams cs784(Prasad) L11Clos
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
CSCE 314: Programming Languages Dr. Dylan Shell
Functions and patterns
Functions and patterns
PROGRAMMING IN HASKELL
Presentation transcript:

CS5205Haskell1 CS5205: Foundations in Programming Languages Overview Lecturer : Chin Wei Ngan Office : S “Language Foundation, Applications and Reasoning

CS5205Haskell2 Administrative Matters Administrative Matters - mainly via Web-page + IVLE - Reading Materials (mostly online): Robert Harper : Foundations of Practical Programming Languages. Free PL books : - Lectures + Assignments + Test + Exam - Assignment (30%) - Test (20%) - Exam (50%)

CS5205Haskell3 Course Objectives Course Objectives - graduate-level course to help build a good foundation - languages as tool for programming - reasoning about programs - explore various applications enabled by languages

CS5205Haskell4 Course Outline Course Outline Lecture Topics (12 weeks + 1 week ) Advanced Language (Haskell) (4 weeks) Type System (3 weeks) Applications enabled by Language (3 weeks) hoogle/darcs user interface parallelism/cloud computing Formal Reasoning & Theorem Proving (2 weeks)

CS5205Haskell5 Advanced Language - Haskell Advanced Language - Haskell Strongly-typed with polymorphism Higher-order functions Pure Lazy Language. Algebraic data types + records Exceptions Type classes, Monads, Arrows, etc Advantages : concise, abstract, reusable Why use Haskell ? programmer productivity

CS5205Haskell6 Type System Type System Abstract description of code + genericity Compile-time analysis that is tractable Guarantees absence of some bad behaviors Issues – expressivity, soundness, completeness, inference? How to use, design and prove type system. Why? detect bugs early

CS5205Haskell7 Some Applications Some Applications Hoogle – search in code library Darcs – distributed version control Programming user interface with arrows.. How to exploit multicore and parallelism?

CS5205Haskell8 Program Reasoning and Proving Program Reasoning and Proving Is sorting algorithm correct? Any memory leaks? Any null pointer dereference? Any array bound violation? What is the your specification/contract? How to verify program correctness? Why? software reliability

CS5205Haskell9 CS5205: Foundations in Programming Languages Haskell A pure lazy functional language that embodies many innovative ideas in language design.

CS5205Haskell10 Haskell Haskell Advanced programming language – reusable, abstract, efficient, feature-rich. Higher-order functions Values, Types and Lazy evaluation Polymorphic Types and Inference Products, Records and Algebraic Types Type-classes, Monads etc Enriched with syntactic sugar and helpful shorthands. Reference --- A Gentle Introduction to Haskell 98

CS5205Haskell11 Values and Types Values and Types As a purely functional language, all computations are done via evaluating expressions (syntactic sugar) to yield values (normal forms as answers). Each expression has a type which denotes the set of possible outcomes. e :: t can be read as expression e has type t. Examples of typings, associating each expression with its corresponding type. 5:: Integer 'a' :: Char [1,2,3] :: [Integer] ('b', 4) :: (Char, Integer) “cs5”:: String (same as [Char])

CS5205Haskell12 Functions and its Type Functions and its Type Functions can be defined by equations with parameters: inc x= x+1 Or through lambda expression (anonymous functions) (\ x -> x+1) They can also be given suitable function typing: inc :: Integer -> Integer (\x -> x+1) :: Integer -> Integer Types can be user-supplied or inferred.

CS5205Haskell13 Expression Evaluation Expression Evaluation Expressions can be evaluated, and reduced to result form. This can be informally represented using: e 1 ) e 2 A concrete example of this is: inc (inc 3) ) 5

CS5205Haskell14 Expression-Oriented Expression-Oriented Conditional expressions are of the form; if e1 then e2 else e3 An example function: Pattern-matching also possible fact :: Integer -> Integer fact n=if n=0 then 1 else n * fact (n-1) fact 0 = 1 fact n= n * fact (n-1)

CS5205Haskell15 Polymorphic Types Polymorphic Types Support tpes that are universally quantified in some way over all types. 8 c. [c] denotes a family of types, for every type c, the type of lists of c. Covers [Integer], [Char], [Integer->Integer], etc. Polymorphism help support reusable code, e.g length :: [a] -> Integer length [] = 0 length (x:xs)= 1 + length xs

CS5205Haskell16 Polymorphic Types Polymorphic Types More examples : length [1,2,3] ) 2 length [‘a’, ’b’, ‘c’] ) 3 length [[1],[],[3]] ) 3 This polymorphic function can be used on list of any type.. head :: [a] -> a head (x:xs)= x tail :: [a] -> [a] tail (x:xs)= xs Note that head/tail are partial functions, while length is a total function?

CS5205Haskell17 Principal Types Principal Types An expression’s principal type is the least general type that contains all instances of the expression. For example, the principal type of head function is [a]->a, while [b] -> a, b -> a, a are correct but too general but [Integer] -> Integer is too specific. Principal type can help supports software reusability with accurate type information. [Char] <: 8 a. [a] <: 8 a. a Some types are more general than others:

CS5205Haskell18 User-Defined Algebraic Types User-Defined Algebraic Types Can also describe a tuple data Bool = False | True data Color= Red | Green | Blue | Violet Can describe enumerations: data Pair = P2 Integer Integer data Point a = Pt a a Pt is a data constructor with type a -> a -> Point a Pt :: Point Float Pt ‘a’ ‘b’:: Point Char Pt True False:: Point Bool

CS5205Haskell19 Recursive Types Recursive Types Two data constructors: data Tree a = Leaf a | Branch (Tree a) (Tree a) Some types may be recursive: Leaf :: a -> Tree a Branch:: Tree a -> Tree a -> Tree a An example function over recursive types: fringe :: Tree a -> [a] fringe (Leaf x)= [x] fringe (Branch left right) = (fringe left) ++ (fringe right)

CS5205Haskell20 Type Synonyms Type Synonyms Type synonyms do not define new types, but simply give new names for existing types. type String = [Char] type Person = (Name, Address) type Name = String data Address = None | Addr String It is possible to provide new names for commonly used types type AssocList a b = [(a,b)] Their use can improve code readibility.

CS5205Haskell21 Built-In Types Built-In Types Tuples are also built-in. data Char = ‘a’ | ‘b’ | … data Int = | … | -1 | 0 | 1 | …. | data Integer = … | -2 | -1 | 0 | 1 | 2 | … They are not special: data (a,b) = M2(a,b) data (a,b,c)= M3(a,b,c) data (a,b.c.d)= M4(a,b,c,d) List type uses an infix operator: data [a] = [] | a : [a] [1,2,3] is short hand for 1 : (2 : (3 : []))

CS5205Haskell22 List Comprehension List Comprehension Captures a list of all f x where x is drawn from xs. More than one generators allowed: [f x | x <- xs] List comprehension is a useful shorthand for building list data structures. Similar to set comprehension notation. [(x,y) | x <- xs, y <- ys] Guards are also permitted. Example : quicksort []= [] quicksot (x:xs)= quicksort [y | y<-xs, y<x] ++ [x] ++ quicksort [y | y =x]

CS5205Haskell23 Arithmetic Sequences and Strings Arithmetic Sequences and Strings String is just a shorthand for list of chars. For example, the string “hello” is a shorthand for [‘h’, ‘e’, ‘l’, ‘l’, ‘o’]. Advantage : standard polymorphic list functions can be used to operate on strings. [1.. 10] ) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] [1, ] ) [1, 3, 5, 7, 9] [1, 4.. ] ) [1, 4, 7, 10, ….. (infinite) Special syntax for arithmetic progression sequence: “hello” ++ “ world” ) “hello world”

CS5205Haskell24 Functions Functions The first version allows a function to be returned as result after applying a single argument. add2 :: (Integer,Integer) -> Integer add2(x,y) = x+y Functions can be written in two main ways: add :: Integer -> Integer -> Integer add x y = x+y inc :: Integer -> Integer inc = add 1 The second version needs all arguments. Same effect requires a lambda abstraction: inc = \ x -> add2(x,1)

CS5205Haskell25 Functions Functions Such higher-order function aids code reuse. Functions can also be passed as parameters. Example: map :: (a->b) -> [a] -> [b] map f [] = [] map f (x:xs)= (f x) : (map f xs) Alternative ways of defining functions: add = \ x -> \ y -> x+y add= \ x y -> x+y map (add 1) [1, 2, 3] ) [2, 3, 4] map add [1, 2, 3] ) [add 1, add 2, add 3]

CS5205Haskell26 Infix Operator Infix Operator Another example is function composition. Infix operators are distinguished entirely by symbols: (++) :: [a]-> [a] -> [a] [] ++ ys = ys (x:xs) ++ ys= x : (xs ++ ys) Infix operator can be coerced to prefix by bracketing, e.g. map (+) [1,2,3] (.):: (b->c) -> (a->b) -> (a->c) f. g = \ x -> f (g x) Alphanumeric named function can be made infix too, e.g. a ‘add’ bx ‘elem’ xs

CS5205Haskell27 Sections Sections Other examples:. Infix operators can also be partially applied: (x+) ´ \y -> x+y (+y) ´ \x -> x+y (+) ´ \x y -> x+y These are syntactic sugar for programming conveniences. inc=(+ 1) add=(+)

CS5205Haskell28 Lazy (non-strict) Functions Lazy (non-strict) Functions They can be avoided by lazy evaluation, e.g. bot= bot Errors such as 3/0 and non-termination such as bot are ill-defined expressions. second bot 3 ) 3 second:: a -> b -> b second x y= y Internally, arguments are converted to thunks (delayed expressions) that are only evaluated on demand. Each thunk is similar to a function with nullary argument.

CS5205Haskell29 Infinite Data Structures Infinite Data Structures They can be accessed in a finite way using functions, such as take, head, etc. ones= 1 : ones numsFrom n= n : numFrom (n+1) squares= map (^ 2) (numsFrom 0) Data constructors are non-strict too which allow us to define infinite data structures, such as : take 5 squares ) [0, 1, 4, 9, 16] head ones ) 1 Non-termination can still occur if we try to access all its components. sum squares ) … (non-terminating!)

CS5205Haskell30 Infinite Data Structures Infinite Data Structures Another example of circularity is. ones= 1 : ones Circular structures are space efficient : fib= 1 : 1 : [a+b | (a,b) <- zip fib (tail fib)] zip (x:xs) (y:ys)= (x,y) : (zip xs ys) zip xs ys = [] This circular fibonacci function can be computed very efficiently.

CS5205Haskell31 Error Function Error Function This can be used in many places to highlight erroneous computation: error:: String -> a There is a special built-in polymorphic function which returns a value that can be accepted by all types: head (x:xs)= x head []= error “argument cannot be []” This can be viewed as an uncaught exception, and is type consistent due to polymorphism.

CS5205Haskell32 Pattern-Matching Pattern-Matching Formal parameters are also patterns though irrefutable. head (x : _)= x tail (_ : xs)= xs Pattern matching is applicable to constructor of any type whether user-defined or built-in : As-pattern provide a convenient way to reuse a pattern. f (x:xs)= x : (x:xs) f x : s Wild-card _ match a value we care nothing about. contrived :: ([a],Char,(Int,Float),String, Bool) -> Bool contrived ([], ‘b’, (1, 2.0), “hi”, True) = False

CS5205Haskell33 Pattern-Matching Semantics Pattern-Matching Semantics Pattern-matching occurs “top-down, left-to-right”. sign x | x > 0= 1 | x==0= 0 | x<0= -1 Pattern matching either fail, succeed or diverge. A successful match will bind the formal parameters in the pattern. Top-level patterns may have boolean guards. [0,bot] matched against pattern [1,2] fails [bot,0] matched against pattern [1,2] diverges

CS5205Haskell34 Case Expression Case Expression take m ys= case (m,ys) of (0,_)-> [] (_, [])-> [] (n,x:xs)-> x : take (n-1) xs if e1 then e2 else e3 ´ case e1 of True -> e2 False -> e3 Case expression is the basic language construct to implement pattern-matching.

CS5205Haskell35 Lazy Patterns Lazy Patterns Another example is circular code with a lazy as-pattern client init resps= init : client (next (head resps)) (tail resps) Irrefutable patterns allow us to support infinite recursive procedures with no base cases. client init ~(r:rs)= init : client (next r) rs fib= 1 : 1 : [a+b | (a,b) <- zip fib (tail fib)] 1 : 1 : [a+b | (a, b) <- zip fib tfib]

CS5205Haskell36 Lexical Scoping Lexical Scoping For scope bindings over guarded expressions, we require a where construct instead: let y = a+b f x = (x+y)/y in f c + f d Local variables can be created by let construct to give nested scope for the name space. Example: f x y | x>z= … | y==z= … | y<z= …. where z=x*x

CS5205Haskell37 Layout Rule Layout Rule is being parsed as: Haskell uses two dimensional syntax that relies on declarations being “lined-up columnwise” Rule : Next character after keywords where/let/of determines the starting columns for declarations. Starting after this point continues a declaration, while starting before this point terminates a declaration. let y = a+b f x = (x+y)/y in f c + f d let { y = a+b ; f x = (x+y)/y } in f c + f d