Advanced Programming Andrew Black and Tim Sheard Lecture 2 Intro to Haskell.

Slides:



Advertisements
Similar presentations
Functional Programming Lecture 10 - type checking.
Advertisements

CMSC 330: Organization of Programming Languages Tuples, Types, Conditionals and Recursion or “How many different OCaml topics can we cover in a single.
ML Datatypes.1 Standard ML Data types. ML Datatypes.2 Concrete Datatypes  The datatype declaration creates new types  These are concrete data types,
ML: a quasi-functional language with strong typing Conventional syntax: - val x = 5; (*user input *) val x = 5: int (*system response*) - fun len lis =
What is a Parser? A parser is a program that analyses a piece of text to determine its syntactic structure  3 means 23+4.
1 ICS103 Programming in C Lecture 3: Introduction to C (2)
A Lightning Tour of Haskell Lecture 1, Designing and Using Combinators John Hughes.
0 PROGRAMMING IN HASKELL Chapter 4 - Defining Functions.
Introduction to ML - Part 2 Kenny Zhu. What is next? ML has a rich set of structured values Tuples: (17, true, “stuff”) Records: {name = “george”, age.
Cse536 Functional Programming 1 6/26/2015 Lecture #1, September 27, 2004 Course Mechanics Text Book Down-loading Haskell Syllabus - Course Overview Functional.
Advanced Programming Andrew Black and Tim Sheard Lecture 4 Intro to Haskell.
0 PROGRAMMING IN HASKELL Chapter 3 - Types and Classes.
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,
CS 2104 : Prog. Lang. Concepts. Functional Programming I Lecturer : Dr. Abhik Roychoudhury School of Computing From Dr. Khoo Siau Cheng’s lecture notes.
Definitions. name :: Type answer :: Int name = expression answer = Definitions associate a name with a value of a certain type is of type greater.
Haskell. 2 GHC and HUGS Haskell 98 is the current version of Haskell GHC (Glasgow Haskell Compiler, version 7.4.1) is the version of Haskell I am using.
0 REVIEW OF HASKELL A lightening tour in 45 minutes.
0 PROGRAMMING IN HASKELL Some first steps Based on lecture notes by Graham Hutton The book “Learn You a Haskell for Great Good” (and a few other sources)
Functional Programming With examples in F#. Pure Functional Programming Functional programming involves evaluating expressions rather than executing commands.
A Second Look At ML 1. Outline Patterns Local variable definitions A sorting example 2.
Overview of the Haskell 98 Programming Language
What is a Type? A type is a name for a collection of related values. For example, in Haskell the basic type Bool contains the two logical values: True.
Introducing Python CS 4320, SPRING Lexical Structure Two aspects of Python syntax may be challenging to Java programmers Indenting ◦Indenting is.
1 CS 457/557: Functional Languages Lists and Algebraic Datatypes Mark P Jones Portland State University.
Introduction to Python Dr. José M. Reyes Álamo. 2 Three Rules of Programming Rule 1: Think before you program Rule 2: A program is a human-readable set.
0 INTRODUCTION TO FUNCTIONAL PROGRAMMING Graham Hutton University of Nottingham.
0 PROGRAMMING IN HASKELL Chapter 4 - Defining Functions.
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:
Haskell Basics CSCE 314 Spring CSCE 314 – Programming Studio Using GHC and GHCi Log in to unix.cse.tamu.edu (or some other server) From a shell.
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,
Guards1. 2 Let’s test this function. Main> maxi Here is a trace of the function: n m maxi 3 2 Guards or conditions are used to express various cases.
0 PROGRAMMING IN HASKELL Chapter 2 - First Steps.
Haskell. GHC and HUGS Haskell 98 is the current version of Haskell GHC (Glasgow Haskell Compiler, version 7.4.1) is the version of Haskell I am using.
An introduction to functional programming using Haskell CENG242 –Recitation 1.
Lecture 16: Advanced Topic: Functional Programming CS5363 Compiler and Programming Languages.
1 PROGRAMMING IN HASKELL Lecture 2 Based on lecture notes by Graham Hutton The book “Learn You a Haskell for Great Good” (and a few other sources)
Quiz 1 A sample quiz 1 is linked to the grading page on the course web site. Everything up to and including this Friday’s lecture except that conditionals.
1 PROGRAMMING IN HASKELL An Introduction Based on lecture notes by Graham Hutton The book “Learn You a Haskell for Great Good” (and a few other sources)
Functional Programming
Principles of programming languages 12: Functional programming
Programming Languages
PROGRAMMING IN HASKELL
Types CSCE 314 Spring 2016.
ML: a quasi-functional language with strong typing
Theory of Computation Lecture 4: Programs and Computable Functions II
Lecture 2:Data Types, Functional Patterns, Recursion, Polymorphism
PROGRAMMING IN HASKELL
A lightening tour in 45 minutes
ICS103 Programming in C Lecture 3: Introduction to C (2)
PROGRAMMING IN HASKELL
Haskell.
CSE 3302 Programming Languages
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
Programming Languages
PROGRAMMING IN HASKELL
Representation, Syntax, Paradigms, Types
Type & Typeclass Syntax in function
PROGRAMMING IN HASKELL
CSCE 314: Programming Languages Dr. Dylan Shell
Haskell Types, Classes, and Functions, Currying, and Polymorphism
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
Presentation transcript:

Advanced Programming Andrew Black and Tim Sheard Lecture 2 Intro to Haskell

Course URLs –Course web page –Links to lecture notes and assignments –Homework submissions –Class mailing list.

Course Evaluation Daily Assignments Class participation, including code walks Projects

Haskell Haskell is a pure functional language. –Yet it supports imperative programming with the use of monads There are several implementations –HUGS - –GHC - Haskell has a sophisticated type system that catches many errors, and supports advanced abstraction mechanisms

Characteristics of Haskell Applicative style –input output description of problem. First class functions –pass as parameters –return as value of a function –store in data-structures Less Importantly: –Automatic memory management (G.C. no new or malloc) –Use of a strong type system which uses type inference, i.e. no declarations but still strongly typed.

GHC or Hugs? Should we use GHC or Hugs? –Hugs is an interpreter Great for quick edit/compile/test turnaround –GHC is a compiler Fast run-time binaries Extensive tool support (profiling) Many extensions For most uses they are compatible, and many programs will run on either system So – I recommend you install and use both!

GHCI the GHC interactive system ___ ___ _ / _ \ /\ /\/ __(_) / /_\// /_/ / / | | GHC Interactive, version 6.4.1, for Haskell 98. / /_\\/ __ / /___| | \____/\/ /_/\____/|_| Type :? for help. Loading package base linking... done. Prelude> length [1,2,3,4] 4 Prelude> In addition to the command-line compiler, GHC also comes with an interactive environment, GHCI, it works much like Hugs (after which it was modeled). Try it out!

The Hugs Interpreter __ __ __ __ ____ ___ _________________________________________ || || || || || || ||__ Hugs 98: Based Haskell 98 standard ||___|| ||__|| ||__|| __|| Copyright (c) ||---|| ___|| World Wide Web: || || Report bugs to: || || Version: Nov 2003 _________________________________________ Hugs mode: Restart with command line option +98 for Haskell 98 mode Hugs session for: C:\Program Files\Hugs98/libraries\Hugs\Prelude.hs C:\Program Files\Hugs98/libraries\Prelude.hs D:\work\sheard\Courses\CSE502\Fall2004\lect01.html Type :? for help Main> Hugs Demo

O.O. vs. Functional Objects behave Functions transform

Basic Approach The basic approach to programming in Haskell is two fold –Define some data structures –Define functions over those data structures In contrast with Smalltalk, where the model is simulation of the real world, the model is transformative. I.e. we think of transforming data from one form to another.

IntLists data IntList = Cons Int IntList | Nil len Nil = 0 len (Cons x xs) = 1 + len xs addAll Nil = 0 addAll (Cons x xs) = x + addAll xs Define some data Write some functions

Data Declarations Data declarations describe tree-like structures allocated in the heap. 3 ConsNil 2 Cons 9 Tag 2 fields, one an Int the other another list 0 fields Note since Nil is a constant, there need be only 1 such cell in the system.

Constructing Data Tree-like structures are created using constructor functions. –These have the same name as the tags –These names always start with an uppercase letter data IntList = Cons Int IntList | Nil (Cons 3 (Cons 2 (Cons 9 Nil))) 3 ConsNil 2 Cons 9

Exercise #1 Define a Haskell Data declaration to capture the following tree-like structure. Data Tree1 = … 9 Fork 9 9 Empty

Exercise #2 Construct the tree using the constructors of your data declaration. 9 Fork 9 9 Empty

Exercise #3 Node 3 Tip 6 14 Tip 8 1.Define a Haskell Data declaration to capture the following tree-like structure. 2.Construct the tree

Functions Functions are defined by cases over the data using patterns. Patterns appear on the left-hand-side of a case. Patterns match tree-like structures and bind variables to values. len Nil = 1 len (Cons x xs) = 1 + len xs

Pattern Construction Patterns are composed of –Constructors –Variables –Constants –Tuples –For example: Cons x xs constructors and variables Cons 5 Nil constructors and constants ( y, Cons x Nil ) tuples, constructors, and variables

Pattern Matching Every pattern matches and binds variables. A pattern can match many structures. E.g. ( Cons x xs ) and Nil 5 Cons Nil x binds to 5 xs binds to Nil

Nested patterns an constants ( Cons x (Cons 5 xs )) matches But NOT 3 ConsNil 5 Cons 9 3 Nil 5 ConsNil 4 Cons 22 Cons 22 Cons 5 Nil (Cons 22 (Cons 5 Nil)) (Cons 3 (Cons 5 (Cons 9 Nil))) (Cons 5 (Cons 4 (Cons 22 Nil))) (Cons 3 Nil)

Selection or Deconstruction Pattern matching is used to select or take apart tree-like heap structures. We can define selection functions using patterns listHead (Cons x xs) = x listTail (Cons x xs) = xs first (x,y) = x second (x,y) = y

A second look len Nil = 0 len (Cons x xs) = 1 + len xs addAll Nil = 0 addAll (Cons x xs) = x + addAll xs empty Nil = True empty (Cons x xs) = False Recursion is the only primitive control structure

Pattern Matching vs Selection addAll Nil = 0 addAll (Cons x xs) = x + addAll xs add2 x = if empty x then 0 else (listHead x) + (add2 (listTail x))

Built in Polymorphic Lists Haskell has a complete set of functions that work on polymorphic lists. [1,4,6] : [Int] [True,False] : [Bool] [Cons 2 Nil] : [ IntList ] Such lists use special syntactic sugar. It is as if they were defined using data [a] = (:) a [a] | []

Special Syntax, but just the same [True,False] or ( True : False : [ ] ) True (:) False (:)[] 1 : (2 : (5 : [])) or [1,2,5] 1 (:) 2 5 [] Right associativity of (:) means we don’t need parentheses.

Functions on polymorhic lists sum :: [ Int ] -> Int sum [] = 0 sum (x : xs) = x + sum xs length :: [ a ] -> Int length [] = 0 length (x : xs) = 1 + length xs null :: [ a ] -> Bool null [] = True null (x : xs) = False Polymorphic type means length works on all kinds of lists.

Strings and characters Strings are nothing more than lists of characters –type String = [ Char ] Strings have special syntax –“abc” is the same as [‘a’, ‘b’, ‘c’] We can access library functions over characters by using the Char library import Char Char.ord :: Char -> Int Char.chr :: Int -> Char

import Char test = Char.ord (head "abc") test2 = Char.chr test test.hs __ __ __ __ ____ ___ _________________________________________ || || || || || || ||__ Hugs 98: Based on the Haskell 98 standard ||___|| ||__|| ||__|| __|| Copyright (c) ||---|| ___|| World Wide Web: || || Report bugs to: || || Version: _________________________________________ Hugs mode: Restart with command line option +98 for Haskell 98 mode Type :? for help Main> :l test.hs Main> test 97 Main> test2 'a' Main>

Tuples Tuples are heterogenous collections of fixed width (4,True) : (Int,Bool) (3,4,5) : (Int,Int,Int) (True,”zx”,False,5) : (Bool, String, Bool, Int)

Pattern matching As we saw in first and second, we can pattern match over tuples. first (x,y) = x second (x,y) = y oneOfThree (x,y,z) = x twoOfThree (x,y,z) = z down2 (((x,y),z),w) = x firstOfHead ((x,y):xs) = x

Mundane issues Lexical issues The offsides rule (indenting matters!) Setting the search path Getting information from Hugs Using Hugs –load files –Change directories –Get type information

Syntactic Elements 1 Literals –Char ‘a’ –Integer 345 –Float –String “abc” Constructors –Constructors start with an Uppercase letter –Primitive operator constructors [] and :

Syntactic Elements 2 Operator chars: operators are combinations of –: # $ % & * + - =. / \ ? ^ | –Reserved operators: (Special sequences of op-chars) :: =.. \ | ~ => Operators are used in an “infix” manner –5 + 3 –(f x) ==> (\ x -> 3 + 4) –Any identifier can be made infix by using backquotes. E.g. 10 `in` w and 3 `choose` 5 –( op ) makes an infix operator a prefix function (+) 4 6

Syntactic Elements 3 Identifiers start with a lower case letter followed by digits or other letters or primes –Valid Examples: a a3 a’b aF –Invalid Examples: F1 Good Reserved words –case class data else –if in infix infixl –infixr instance let of –primitive then type where

Syntax 3 The offside rule. Indentation matters –Continuation across lines with deeper indentation continues the same declaration. –Less indentation means the start of the next declaration. –Consequence ALL DECLARATIONS IN THE SAME GROUP MUST BE EQUALLY INDENTED.

OK length [] = 0 length (x : xs) = 1 + length xs null [] = True null (x : xs) = False

NOT OK length [] = 0 length (x : xs) = 1 + length xs null [] = True null (x : xs) = False

Indentation matters at top level and Case f x = case x of [] -> 0 (x:xs) -> 1 + f x Let let f (x,y) = x a = f (2,3) in a Where f x = g init x where g init [] = init g init (x:xs) = g (init + x) xs init = 5

Hugs Hugs has two modes –Command mode : command –Evaluation mode expression

Expression Evaluation ? :cd /ogi/staff/sheard/cse502 ? ? 5 * ? sqrt ? sum [2,3,4] 9 ? length [2,3,4,5] 4 ? sort [3,4,1,2,77,6] [1, 2, 3, 4, 6, 77] ?

Hugs Help- : Main> :? LIST OF COMMANDS: Any command may be abbreviated to :c where c is the first character in the full name. :load load modules from specified files :load clear all files except prelude :also read additional modules :reload repeat last load command :edit edit file :edit edit last module :module set module for evaluating expressions evaluate expression :type print type of expression :? display this list of commands :set set command line options :set help on command line options :names [pat] list names currently in scope :info describe named objects :browse browse names exported by :find edit module containing definition of name :!command shell escape :cd dir change directory :gc force garbage collection :version print Hugs version :quit exit Hugs interpreter Main>

Command: typing expressions Main> Main> :t sort sort :: Ord a => [a] -> [a] Main> :t mymap mymap :: (a -> b) -> [a] -> [b] Main> :t mymap (\x -> x+1) mymap (\x -> x + 1) :: Num a => [a] -> [a] Main>

Functions Functions are defined in Files and loaded into to Hugs. Example: :l lect01.hs Functions on numbers –Type of numbers: Int and Float –Conversion functions: fromInteger round Functions on Booleans –Relational operators = == /= –Combinators && || not Examples ? 5 > 7 False ? 1==4 False

Function Definitions Functions defined in files by writing equations visit a sample file.hs Example: plusone x = x + 1 Sample Output when loading: Hugs session for: E:\programs\Hugs98Dec01\\lib\Prelude.hs E:\work\sheard\Courses\CSE502\web\lecturenotes\lect 01.hs Type :? for help Main> ? plusone plusone ? plusone 4 5

Functions with Multiple Arguments Example Definitions difference x y = x - y choose x y z = if x then y else z Example Session: Hugs session for: E:...\lect01.hs ? :type difference difference :: Int -> Int -> Int ? :type choose choose :: Bool -> a -> a -> a ? Arrow is right Associative a -> b -> c = a -> (b -> c)

Setting the search path When hugs looks for libraries and modules, it looks in the directories denoted by the search path. :set –will display the path (and lots of other things) :set -P;c:\xxx;d:\yyy –will add c:\xxx and d:\yyy to the existing path (indicated by the leading semicolon)

Types of Errors Syntax errors (use of symbols in unexpected places) f x = (x*0) = x ? :r Reading script file "lect01.hs": Parsing ERROR "lect01.hs" (line 36): Syntax error in input (unexpected `=') ? Undefined variables lastone2 = head. rev ? :r Reading script file "lect01.hs": Dependency analysis ERROR "lect01.hs" (line 38): Undefined variable "rev" ?

Types of Errors (cont.) Type errors ? :type hd hd :: [a] -> a ? :type plusone plusone :: Int -> Int ? hd 3 ERROR: Type error in application *** expression : hd 3 *** term : 3 *** type : Int *** does not match : [a] ? plusone [1,2] ERROR: Type error in application *** expression : plusone [1,2] *** term : [1,2] *** type : [Int] *** does not match : Int

Assignment #2 You are to write a number of functions in Haskell –explode:: String -> [Char] –digitValue:: [Char] -> [Int] –reverse:: [Int] -> [Int] –pairedWithPowersOf10:: [Int] -> [(Int,Int)] –pairWiseProduct ::[(Int,Int)] -> [Int] –sum :: [Int] -> Int –toInt :: String -> Int Write 5 functions (sum & reverse are primitives, and don’t need to be written). Write each one using pattern matching and recursion. Create a number of tests for each function –test1 = explode “tim” == [‘t’, ‘i’, ‘m’] Turn in an elegant program that communicates your solution well.