Transcript Lecture 4
GC16/3011 Functional Programming
Lecture 4
Miranda
(and her friend Amanda)
3/29/2016
1
Contents
•
•
•
•
•
•
•
Miranda/Amanda
Amanda demonstration
Comments
Legal names and binding
Types and type checking
Tuples
Simple functions
3/29/2016
2
Amanda
•
•
•
PC version of Miranda
Almost (but not quite) the same!
Get it from the Web pages
•
•
http://www.cs.ucl.ac.uk/teaching/3C11/index.html
Amanda204:
• http://www.engineering.tech.nhl.nl/engineering/
personeel/bruin/data/amanda204.zip
3/29/2016
3
Amanda Demonstration
•
Lambda Calculus
•
•
But you can gives names to
(sub)expressions
•
•
•
•
(3 + 4) * (6 + 7)
x=3+4
y=6+7
main = (x * y)
Also give names to functions (no lambdas!)
•
•
inc x = x + 1
main = inc 56
3/29/2016
4
Amanda Demonstration
•
•
•
•
•
Interpretive environment
Use it as a calculator
Simple definitions stored in a file
Main definition
Define and use functions
3/29/2016
5
Comments
•
•
•
VERY important!
Use them from the start
Example:
|| a simple definition for some text:
message = “hello mum”
|| here is a function which adds one to a number:
inc x = x + 1
3/29/2016
6
Legal names
•
BINDING:
•
•
•
•
•
NAME = EXPRESSION
Funcname argname = EXPRESSION
• Binds funcname when defined (static)
• Binds argname when applied to an argument (dynamic)
Each binding is unique, within specified scope
• Scope of argname is the function body (only)
• Nested scopes (see later) permit nested bindings for same name
Names MUST start with an alphabetic character
Names MUST NOT start with a capital letter!
•
but may contain numbers and underscores
3/29/2016
7
Types
•
Data can be, for example:
•
•
•
•
•
•
•
•
Numbers (42): num
Characters (‘A’): char
Text (“strings”): [char]
Truth values (True, False): bool
Functions (f x = x + 1): arg_type -> result_type
Miranda/Amanda allows us to CATEGORISE data into
specific types
Helps organise programs better
Helps detect errors
3/29/2016
8
Type Checking
•
Done before the program is run
•
Checks that operators (e.g. +) are executed on data of the
correct type
•
Checks that functions are applied to data of the correct
type
•
You can ask “what type is this?”
•
You can specify “this is a Boolean value” etc.
3/29/2016
9
Tuples
•
A simple data structure
•
(“Sheila Bloggs”, 23, “2 Turnabout Road, NW3”, 60,
False)
•
(34, True) :: (num, bool)
•
(34, True) DOES NOT EQUAL (True, 34)
•
(“increment”, (+ 1), inc)
:: ([char], num->num, num->num)
3/29/2016
10
Simple Functions
inc x = x + 1
|| the hello function
hello :: num -> [char]
hello x = “good morning”, if (x<10)
= “goodbye”, otherwise
3/29/2016
11
Summary
•
•
•
•
•
•
•
Miranda/Amanda
Amanda demonstration
Comments
Legal names and binding
Types and type checking
Tuples
Simple functions
3/29/2016
12