modeling with haskell scientific seminar 03/04 gerhard navratil
TRANSCRIPT
Modeling with Haskell
Scientific Seminar 03/04Gerhard Navratil
Contents
Functional Programming
Haskell
Modeling
Example
Functional Programming
“Everything is a function” Parameters to result
Different from imperative programming – no side effects!
ParametersFunction
Result
Key Elements
Recursion replaces loops No side effects No change of value (x = x+1)
‘Easy’ to read‘Easy’ to testMathematically clean
Constants and Test Data
… are functions, too
Constants are constant functionse.g. pi = 3.1415927…
Test data are modeled as constants
Testing the Model
Imperative programming: Debugger No Debugger necessary for functional
programming! Each function tested separately No side effects the function will
always react like that Never forget: Special cases (Div by
Zero)
Haskell
The Syntax
Predefined typesBool, Int, Integer, Float, Double, Rational, Char, String, Pairs, Lists Maybe
Type of a functionname :: T1 -> T2 -> … Tn -> Tr
Implementation of a functionname v1 v2 … vn = res
Examples increment :: Int -> Int
increment x = x + 1 Quadratic polynom:
root :: (Float,Float,Float) -> (Float,Float)
root (a,b,c) = (x1,x2) where x1 = e + sqrt d / ( 2 * a ) x2 = e – sqrt d / ( 2 * a ) d = b * b – 4 * a * c e = - b / ( 2 * a )
a
acb
a
bx
2
4
2
2
2,1
Indentation matters!
Lists
List = Structure that holds any number of elements of the same type
List of Integers, Stings, Booleans, … Strings are lists of characters
e.g. [1,2,3], [‘a’, ‘b’], [] Building: 1 : [2,3] [1,2,3]
Working with Lists: Recursion sumList :: [Int] -> Int
sumList [] = 0sumList (x:xs) = x + sumList xs
Usually hidden inside other functions: head, tail, take sumList x = head x + sumList (tail s) length, reverse, ++ 2nd order: map, filter, fold, zip
Example map
Coding of texts:
coding :: String -> [Int]coding s = map ord s
coding “Navratil”[78,97,118,114,97,116,105,108]
Example filter
Filtering numbers:
filter_even :: [Int] -> [Int]filter_even ns = filter even ns
filter_even [1,2,3,4,5][2,4]
Example fold
Summing up all numbers in a list:
addAll :: [Int] -> IntaddAll ns = foldl (+) 0 ns
addAll [1,3,5]9
Example zip
Combining neighboring elements of a list:
neighbors :: [Int] -> [(Int,Int)]neighbors x = zip (take (length x - 1) x) (tail x)
neighbors [1,2,3][(1,2),(2,3)]
Representation of Data Type-synonyms
type Name = Stringtype Year = Inttype Month = Inttype Dat = Int
User-defined data typesdata DayOfWeek = Mon | Tue | …data Birthday = B Year Month Daydata Employee = E Name Birthday
Using Data Types n :: Name
n = “Gerhard Navratil”
e :: Employeee = E n (B 1969 8 25)
hire :: Employee -> [Employee] -> [employee]hire e []
Parametrized Data Types data List a = L a (List a) | Empty
li1, li2, li3 :: List Integerli1 = Emptyli2 = L 1 li1li3 = L 5 li2
li3L 5 (L 1 Empty)
Polymorphism
Roots of the quadratic equationroots :: (Floating a) => (a,a,a) -> (a,a)
Length of a listlength :: [a] -> Intlength [] = 0length (_:xs) = 1 + length xs
Function Composition
Math: f (g (x)) = (g f) (x)
Haskell: (g . f) xResult type of f = Parameter type of g
take (length x - 1) x(reverse . tail . reverse) x
Guards Sign function:
sign x | x < 0 = -1| x == 0 = 0| x > 0 = 1
0:
0:
0:
1
0
1
x
x
x
xsign
List Comprehension
[x | x <- [0 .. 100], odd x]
f xs ys = [x*y | x<-xs, y<-ys]
map f xs = [f x | x <- xs]
filter p xs = [x | x <- xs, p x]
Modeling
Algebraic Modeling
Set of sorts S Set of Operators O Set of Axioms for the operators
Example 2D Vector sorts: Vec, Float operations make: Float Float -> Vec
getX: Vec -> FloatgetY: Vec -> Floatadd: Vec Vec -> Vecsub: Vec Vec -> Vec
axiomsadd a,b = make (getX a + getX b) (getY a + getY b)sub a,b = make (getX a – getX b) (getY a – getY b)
Example 2D Vector in Haskell
class Vector vec where make ::Float -> Float -> vec getX, getY :: vec -> Float add, sub :: vec -> vec -> vec
add a b = make (getX a + getX b) (getY a + getY b)
sub a b = make (getX a – getX b) (getY a – getY b)
Instances Connection between classes and data types
type V2 = (Float, Float)instance Vector V2 where make x y = (x,y) getX (x,y) = x getY (x,y) = y
Same procedure fordata V2_2 = V Float Float
Modeling is …
Defining elements
Combining elements
Until the model is as complete as we want it
Example Database
Database Elements Have an identifier Have attributes
type Attrib = (String, String)class Objects o where object :: ID -> [Attrib] -> o getID :: o -> ID getAtts :: o -> [Attrib] getAttN :: String -> o -> String getAttN n o =
(snd.head.filter((n==).fst).getAtts) o
Database Put objects in the DB Read objects from the DB Change objects in the DB
class (Objects o) => Databases d owhere
empty :: d o getLastID :: d o -> ID insert :: [Attrib] -> [d o] -> [d o] select :: ID -> d o -> o …
Cadasterclass (Databases c d, ListFuncs d) => Cadasters c d where inscribe :: c d -> d -> c d data2Doc :: c d -> d -> d formalTest :: c d -> d -> Bool register :: c d -> d -> c d test :: c d -> d -> Bool dbChanges :: c d -> d -> c d inscribe c d = if (formalTest c d) &&
(test rc nd) then dbChanges rc nd else c where rc = register c a nd = data2Doc rc a
Cadastral Requests
class Cadasters c d => Requests c d where
owner :: c d -> ID -> d documents :: c d -> ID -> [d]
Further Reading Books:
Simon Peyton Jones: “Haskell 98 Language and Libraries”, Cambridge University Press, 2003, 272 pages.
Simon Thompson: “Haskell: The Craft of Functional Programming”, 2nd Edition, Addison-Wesley, 1999, 507 pages.
Richard Bird: “Introduction to Functional Programming using Haskell”, 2nd edition, Prentice Hall Press, 1998, 460 pages.
Tutorial texts are available on: www.haskell.org