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)

Slides:



Advertisements
Similar presentations
ML: a quasi-functional language with strong typing Conventional syntax: - val x = 5; (*user input *) val x = 5: int (*system response*) - fun len lis =
Advertisements

Functional Programming Universitatea Politehnica Bucuresti Adina Magda Florea
Using Types Slides thanks to Mark Jones. 2 Expressions Have Types: The type of an expression tells you what kind of value you might expect to see if you.
The > prompt means that the system is ready to evaluate an expression. For example: > 2+3*4 14 > (2+3)*4 20 > sqrt (3^2 + 4^2) 5.0.
0 PROGRAMMING IN HASKELL Chapter 5 - List Comprehensions.
0 PROGRAMMING IN HASKELL Chapter 4 - Defining Functions.
0 PROGRAMMING IN HASKELL Chapter 2 - First Steps.
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,
Using Types Slides thanks to Mark Jones. 2 Expressions Have Types: The type of an expression tells you what kind of value you might expect to see if you.
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.
0 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 in Haskell Motivation through Concrete Examples Adapted from Lectures by Simon Thompson.
Tuples and Lists Lecture 3, Programmeringsteknik del A.
0 PROGRAMMING IN HASKELL Chapter 5 – Introduction, The Hugs System, Types and Classes.
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 Chapter 7 - Defining Functions, List Comprehensions.
Dan Johnson.  Functional language that started development in  Committee designed language  Pure and Lazy  Compiled or Interpreted  Named after.
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)
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.
0 INTRODUCTION TO FUNCTIONAL PROGRAMMING Graham Hutton University of Nottingham.
0 PROGRAMMING IN HASKELL Chapter 4 - Defining Functions.
Lee CSCE 314 TAMU 1 CSCE 314 Programming Languages Haskell: More on Functions and List Comprehensions Dr. Hyunyoung Lee.
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,
0 PROGRAMMING IN HASKELL Chapter 2 - First Steps.
Functional Programming Lecture 3 - Lists Muffy Calder.
Haskell Chapter 5, Part II. Topics  Review/More Higher Order Functions  Lambda functions  Folds.
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.
Lecture 16: Advanced Topic: Functional Programming CS5363 Compiler and Programming Languages.
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)
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.
6-Jul-16 Haskell II Functions and patterns. Data Types Int + - * / ^ even odd Float + - * / ^ sin cos pi truncate Char ord chr isSpace isUpper … Bool.
Lecture 14: Advanced Topic: Functional Programming
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}
Polymorphic Functions
Functional Programming
Conditional Expressions
Midterm recap Total was 80 points Distribution range
dr Robert Kowalczyk WMiI UŁ
PROGRAMMING IN HASKELL
Types CSCE 314 Spring 2016.
Theory of Computation Lecture 4: Programs and Computable Functions II
Haskell Chapter 2.
PROGRAMMING IN HASKELL
A lightening tour in 45 minutes
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
Haskell.
CSE 3302 Programming Languages
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
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
Functions and patterns
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
Presentation transcript:

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)

2 Glasgow Haskell Compiler  GHC is the leading implementation of Haskell, and comprises a compiler and interpreter;  The interactive nature of the interpreter makes it well suited for teaching and prototyping;  GHC is freely available from:

3 Starting GHC % ghci GHCi, version 7.4.1: :? for help Loading package ghc-prim... linking... done. Loading package integer-gmp... linking... done. Loading package base... linking... done. Prelude> The GHC interpreter can be started from the Unix command prompt % by simply typing ghci:

4 Useful GHCi Commands CommandMeaning :load nameload script name :reloadreload current script :edit nameedit script name :editedit current script :type exprshow type of expr :?show all commands :quitquit GHCi

5 Naming Requirements  Function and argument names must begin with a lower-case letter. For example: myFunfun1arg_2x’  By convention, list arguments usually have an s suffix on their name. For example: xsnsnss

6 The Layout Rule In a sequence of definitions, each definition must begin in precisely the same column: a = 10 b = 20 c = 30 a = 10 b = 20 c = 30 a = 10 b = 20 c = 30

7 means The layout rule avoids the need for explicit syntax to indicate the grouping of definitions. a = b + c where b = 1 c = 2 d = a * 2 a = b + c where {b = 1; c = 2} d = a * 2 implicit grouping explicit grouping

8 Exercise n = a ’div’ length xs where a = 10 xs = [1,2,3,4,5] Fix the syntax errors in the program below, and test your solution using GHCi. (Copy your corrected version into an to me, but don’t send yet.)

9 What is a Type? A type is a name for a collection of related values. For example, in Haskell the basic type TrueFalse Bool contains the two logical values:

10 Type Errors Applying a function to one or more arguments of the wrong type is called a type error. > 1 + False Error 1 is a number and False is a logical value, but + requires two numbers.

11 Types in Haskell  If evaluating an expression e would produce a value of type t, then e has type t, written e :: t  Every well formed expression has a type, which can be automatically calculated at compile time using a process called type inference.

12  All type errors are found at compile time, which makes programs safer and faster by removing the need for type checks at run time.  In GHCi, the :type command calculates the type of an expression, without evaluating it: > not False True > :type not False not False :: Bool

13 Basic Types Haskell has a number of basic types, including: Bool - logical values Char - single characters Integer - arbitrary-precision integers Float - floating-point numbers String - strings of characters Int - fixed-precision integers

14 List Types [False,True,False] :: [Bool] [’a’,’b’,’c’,’d’] :: [Char] In general: A list is sequence of values of the same type: [t] is the type of lists with elements of type t.

15  The type of a list says nothing about its length: [False,True] :: [Bool] [False,True,False] :: [Bool] [[’a’],[’b’,’c’]] :: [[Char]] Note:  The type of the elements is unrestricted. For example, we can have lists of lists:

16 Tuple Types A tuple is a sequence of values of different types: (False,True) :: (Bool,Bool) (False,’a’,True) :: (Bool,Char,Bool) In general: (t1,t2,…,tn) is the type of n-tuples whose ith components have type ti for any i in 1…n.

17  The type of a tuple encodes its size: (False,True) :: (Bool,Bool) (False,True,False) :: (Bool,Bool,Bool) (’a’,(False,’b’)) :: (Char,(Bool,Char)) (True,[’a’,’b’]) :: (Bool,[Char]) Note:  The type of the components is unrestricted:

18 Function Types not :: Bool  Bool isDigit :: Char  Bool In general: A function is a mapping from values of one type to values of another type: t1  t2 is the type of functions that map values of type t1 to values to type t2.

19  The arrow  is typed at the keyboard as ->.  The argument and result types are unrestricted. For example, functions with multiple arguments or results are possible using lists or tuples: Note: add :: (Int,Int)  Int add (x,y) = x+y zeroto :: Int  [Int] zeroto n = [0..n]

20 Exercise [’a’,’b’,’c’] (’a’,’b’,’c’) [(False,’0’),(True,’1’)] ([False,True],[’0’,’1’]) [tail,init,reverse] What are the types of the following values? (Again, add this to that .)

21 Exercise Prelude> myLast [1,2,3,4] 4 Prelude> myLast [‘x’,’y’,’z’] z Write a function in your script that will find the last element in a list. For example: Note that your first line should be declaration plus type, and from there use pattern matching and recursion. (Again, add this to that .)

22 Functions with multiple arguments are also possible by returning functions as results: add’ :: Int  (Int  Int) add’ x y = x+y add’ takes an integer x and returns a function add’ x. In turn, this function takes an integer y and returns the result x+y. Curried Functions

23  add and add’ produce the same final result, but add takes its two arguments at the same time, whereas add’ takes them one at a time: Note:  Functions that take their arguments one at a time are called curried functions, celebrating the work of Haskell Curry on such functions. add :: (Int,Int)  Int add’ :: Int  (Int  Int)

24  Functions with more than two arguments can be curried by returning nested functions: mult :: Int  (Int  (Int  Int)) mult x y z = x*y*z mult takes an integer x and returns a function mult x, which in turn takes an integer y and returns a function mult x y, which finally takes an integer z and returns the result x*y*z.

25 Why is Currying Useful? Curried functions are more flexible than functions on tuples, because useful functions can often be made by partially applying a curried function. For example: add’ 1 :: Int  Int take 5 :: [Int]  [Int] drop 5 :: [Int]  [Int]

26 Currying Conventions  The arrow  associates to the right. Int  Int  Int  Int To avoid excess parentheses when using curried functions, two simple conventions are adopted: Means Int  (Int  (Int  Int)).

27  As a consequence, it is then natural for function application to associate to the left. mult x y z Means ((mult x) y) z. Unless tupling is explicitly required, all functions in Haskell are normally defined in curried form.

28 Polymorphic Functions A function is called polymorphic (“of many forms”) if its type contains one or more type variables. length :: [a]  Int for any type a, length takes a list of values of type a and returns an integer.

29  Type variables can be instantiated to different types in different circumstances: Note:  Type variables must begin with a lower-case letter, and are usually named a, b, c, etc. > length [False,True] 2 > length [1,2,3,4] 4 a = Bool a = Int

30  Many of the functions defined in the standard prelude are polymorphic. For example: fst :: (a,b)  a head :: [a]  a take :: Int  [a]  [a] zip :: [a]  [b]  [(a,b)] id :: a  a

31 As already discussed, Haskell has extraordinary range capability on lists: ghci> [1..15] [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15] ghci> ['a'..'z'] "abcdefghijklmnopqrstuvwxyz" ghci> ['K'..'Z'] "KLMNOPQRSTUVWXYZ” ghci> [2,4..20] [2,4,6,8,10,12,14,16,18,20] ghci> [3,6..20] [3,6,9,12,15,18] Ranges in Haskell

32 But be careful: ghci> [0.1, ] [0.1,0.3,0.5,0.7, , ] Ranges in Haskell (I’d recommend just avoiding floating point in any range expression in a list – imprecision is just too hard to predict.)

33 Can be very handy – these are equivalent: [13,26..24*13] take 24 [13,26..] Infinite Lists A few useful infinite list functions: ghci> take 10 (cycle [1,2,3]) [1,2,3,1,2,3,1,2,3,1] ghci> take 12 (cycle "LOL ") "LOL LOL LOL " ghci> take 10 (repeat 5) [5,5,5,5,5,5,5,5,5,5]

34 Very similar to standard set theory list notation: ghci> [x*2 | x <- [1..10]] [2,4,6,8,10,12,14,16,18,20] List Comprehensions Can even add predicates to the comprehension: ghci> [x*2 | x = 12] [12,14,16,18,20] ghci> [ x | x <- [ ], x `mod` 7 == 3] [52,59,66,73,80,87,94]

35 Can even combine lists: ghci> let nouns = ["hobo","frog","pope"] ghci> let adjectives = ["lazy","grouchy","scheming"] ghci> [adjective ++ " " ++ noun | adjective <- adjectives, noun <- nouns] ["lazy hobo","lazy frog","lazy pope","grouchy hobo","grouchy frog", "grouchy pope","scheming hobo","scheming frog","scheming pope"] List Comprehensions

36 Write a function called myodds that takes a list and filters out just the odds using a list comprehension. Then test it by giving it an infinite list, but then only “taking” the first 12 elements. Note: Your code will start with something like: myodds xs = [ put your code here ] Exercise