An Introduction To Programming in Haskell: Mark P Jones Portland State University
An Introduction To Programming in Haskell: Mark P Jones Portland State University
Programming in Haskell
Mark P Jones
Portland State University
1
Haskell Resources:
Haskell Resources:
The focal point for information about
Ill be using:
Online tutorials/references:
learnyouahaskell.com
book.realworldhaskell.org
3
Textbooks:
What is Functional
Programming?
Functions:
In a pure functional language:
Example:
Write a program to add up the
numbers from 1 to 10
int tot = 0;
for (int i=1; i<10; i++)
tot = tot + i;
iteration
update
update
implicit result returned in the variable tot
10
In ML:
accumulating parameter
(tail) recursion
In Haskell:
sum [1..10]
combining
function
Computing by Calculating:
Calculators are a great tool
for manipulating numbers
Buttons for:
entering digits
combining values
using stored values
42.0!
14
Computing by Calculating:
What if we could calculate
with other types of value?
Buttons for:
entering pixels
combining pictures
using stored pictures
15
Computing by Calculating:
Spreadsheets are
Values can be
16
Functional Languages:
Multiple types of data
18
Starting Hugs:
user$ hugs
__
__ __ __ ____
___
||
|| || || || || ||__
||___|| ||__|| ||__|| __||
||---||
___||
||
||
||
|| Version: September 2006
_________________________________________
Hugs 98: Based on the Haskell 98 standard
Copyright (c) 1994-2005
World Wide Web: http://haskell.org/hugs
Bugs: http://hackage.haskell.org/trac/hugs
_________________________________________
Haskell 98 mode: Restart with command line option -98 to enable extensions
Type :? for help
Hugs>
quit
:l file
load file
:e file
edit file
Expr
evaluate expression
19
20
Simple Expressions:
Expressions can be constructed using:
The usual arithmetic operations:
1+2*3
Comparisons:
1 == 2
'a' < 'z'
Boolean operators:
True && False
not False
Built-in primitives:
odd 2
sin 0.5
Parentheses:
odd (2 + 1)
(1 + 2) * 3
Etc
21
22
Type Errors:
Hugs> 'a' && True
ERROR - Type error
*** Expression
*** Term
*** Type
*** Does not match
in application
: 'a' && True
: 'a'
: Char
: Bool
Hugs> odd 1 + 2
ERROR - Cannot infer instance
*** Instance
: Num Bool
*** Expression : odd 1 + 2
Hugs>
23
Pairs:
A pair packages two values into one
(1, 2)
('a', 'z')
(True, False)
('a', False)
(True, 2)
24
Operating on Pairs:
There are built-in functions for
extracting the first and second
component of a pair:
fst (True, 2) = True
snd (0, 7) = 7
25
Lists:
Lists can be used to store zero or more
[1, 2, 3]
['a', 'z']
26
Operating on Lists:
There are built-in functions for extracting
27
28
Continued
Selecting an element (by position):
[1,2,3,4,5] !! 3 = 4
29
Arithmetic sequences:
[1..10] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[1,3..10] = [1, 3, 5, 7, 9]
Comprehensions:
[ 2 * x | x <- [1,2,3,4,5] ] = [2, 4, 6, 8, 10]
[ y | y <- [1,2,3,4], odd y ] = [ 1, 3 ]
30
Functions:
The type of a function that maps
Examples:
odd :: Int -> Bool
fst :: (a, b) -> a
(a,b are type variables)
length :: [a] -> Int
32
Operations on Functions:
Function Application. If f :: A -> B and x ::
A, then f x :: B
33
Sections:
If is a binary op of type A -> B -> C,
then we can use sections:
()
:: A -> B -> C
(expr ) :: B -> C
(assuming expr::A)
( expr) :: A -> C
(assuming expr::B)
Examples:
Higher-order Functions:
map :: (a -> b) -> [a] -> [b]
35
Definitions:
So far, weve been focusing on expressions
that we might want to evaluate.
Simple Definitions:
Put the following text in a file defs.hs:
greet name = "hello " ++ name
square x = x * x
fact n = product [1..n]
37
38
Using Libraries:
Many useful functions are provided as part
of the Prelude
Many more are provided by libraries that
must be imported before they can be used
Example:
import Char
nextChar c = chr (1 + ord c)
39
Typeful Programming:
Types are an inescapable feature of
programming in Haskell
Type Synonyms:
41
Type Synonym:
A type synonym (or type abbreviation) gives
a new name for an existing type.
Examples:
type
type
type
type
type
type
String
Length
Angle
Radius
Point
Set a
= [Char]
= Float
= Float
= Length
= (Float, Float)
= a -> Bool
42
Algebraic Datatypes:
43
In Haskell Notation:
data Bool = False | True
introduces:
A type, Bool
A constructor function, False :: Bool
A constructor function, True :: Bool
More Enumerations:
data Rainbow = Red | Orange | Yellow
| Green | Blue | Indigo | Violet
introduces:
A type, Rainbow
A constructor function, Red :: Rainbow
A constructor function, Violet :: Rainbow
45
= Circle Radius
| Rect Length Length
| Transform Transform Shape
data Transform
= Translate Point
| Rotate Angle
| Compose Transform Transform
introduces:
Two types, Shape and Transform
Circle :: Radius -> Shape
Rect :: Length -> Length -> Shape
Transform :: Transform -> Shape -> Shape
46
Nil
:: List Rainbow
Cons Red Nil
:: List Rainbow
Cons Blue (Cons Red Nil) :: List Rainbow
47
Pattern Matching:
In addition to introducing a new type and a
Example:
first
first (x, y)
:: (a, b) -> a
=x
wavelengths
:: Rainbow -> (Length,Length)
wavelengths Red
= (620*nm, 750*nm)
wavelengths Orange = (590*nm, 620*nm)
nm = 1e-9 :: Float
48
More Examples:
head
head []
head (x:xs)
:: [a] -> a
= error head of []
=x
length
length []
length (x:xs)
area
area (Circle r)
area (Rect w h)
area (Transform t s)
Examples:
[] does not match the pattern (x:xs)
[1,2,3] matches the pattern (x:xs) with
x=1 and xs=[2,3]
50
Patterns:
More formally, a pattern is either:
An identifier
An underscore (a wildcard)
Function Definitions:
In general, a function definition is written as
a list of adjacent equations of the form:
f p1 pn = rhs
where:
continued:
Given a function definition with m
equations:
f p1,1 pn,1 = rhs1
f p1,2 pn,2 = rhs2
Example: filter
filter
:: (a -> Bool) -> [a] -> [a]
filter p []
= []
filter p (x:xs)
|px
= x : rest
| otherwise = rest
where rest = filter p xs
guards
where clause
55
insert
insert n Leaf
insert n (Fork l m r)
| n <= m
| otherwise
lookup
:: Int -> Tree -> Bool
lookup n Leaf
= False
lookup n (Fork l m r)
|n<m
= lookup n l
|n>m
= lookup n r
| otherwise
= True
56
Summary:
An appealing, high-level approach to
program construction in which
independent aspects of program
behavior are neatly separated
57
Assignment #1
Your goal is to write a function:
Write definitions for four of these functions (reverse and sum are builtin), using pattern matching and recursion where necessary
58