Upload
others
View
15
Download
0
Embed Size (px)
Citation preview
Young Won Lim7/27/16
Haskell Overview (1A)
Young Won Lim7/27/16
Copyright (c) 2016 Young W. Lim.
Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.2 or any later version published by the Free Software Foundation; with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts. A copy of the license is included in the section entitled "GNU Free Documentation License".
Please send corrections (or suggestions) to [email protected].
This document was produced by using OpenOffice.
Haskell Overview 3 Young Won Lim7/27/16
Based on
Haskell Tutorial, Medak & Navratilftp://ftp.geoinfo.tuwien.ac.at/navratil/HaskellTutorial.pdf
Yet Another Haskell Tutorial, Daumehttps://www.umiacs.umd.edu/~hal/docs/daume02yaht.pdf
Haskell Overview 4 Young Won Lim7/27/16
Function Declaration and Definition
increment x = x + 1
increment :: Int -> Intfunction name arg type return type
Int increment ( Int )
Int arg Int return
increment 2
3 :: Int
Haskell Overview 5 Young Won Lim7/27/16
Function Examples
and1 a b = if a == b then aelse False
and1 :: Bool -> Bool -> Bool function name arg1 type return type
Bool and1 ( Bool, Bool )
Bool arg1, arg2 Bool return
arg2 type
Haskell Overview 6 Young Won Lim7/27/16
Several Function Definitions
and1 :: Bool -> Bool -> Bool and1 True True = Trueand1 x y = False
and1 :: Bool -> Bool -> Bool and1 True True = Trueand1 _ _ = False
Rule (I)
Rule (II)
Rule (I)
Rule (II)
wild character
Haskell Overview 7 Young Won Lim7/27/16
Where Statement – Local Definition
roots :: (Float, Float, Float) -> (Float, Float)
roots (a, b, c) = (x1, x2) wherex1 = e + sqrt d / (2*a)x2 = e – sqrt d / (2*a) d = b*b – 4*a*c e = – b / (2*a)
Input tuple Output tuple
the same indentation
without using { } as in C
No tab
Haskell Overview 8 Young Won Lim7/27/16
Function Call Results
? roots p1 (-1.0,-1.0) :: (Float, Float)(94 reductions, 159 cells)
? roots p2 ( Program error: {primSqrtFloat (-3.0)}(61 reductions,183 cells)
p1, p2 :: (Float, Float, Float)p1 = (1.0, 2.0, 1.0)p2 = (1.0, 1.0, 1.0)
Variable declaration
p1 assignment
p2 assignment
Haskell Overview 9 Young Won Lim7/27/16
If-then-else Statement
roots :: (Float, Float, Float) -> (Float, Float)
roots (a, b, c) = do if d < 0
then error “sorry”else (x1, x2)
wherex1 = e + sqrt d / (2*a)x2 = e – sqrt d / (2*a) d = b*b – 4*a*c e = – b / (2*a)
Input tuple Output tuple
Indentation
No Tab
Haskell Overview 10 Young Won Lim7/27/16
Simple List Functions
map Data.Char.toUpper "Hello World"
"HELLO WORLD"
filter Data.Char.isLower "Hello World"
"elloorld"
the same number of list elements
fewer number of list elements
Haskell Overview 11 Young Won Lim7/27/16
Simple List Functions – foldr function
foldr (-) 1 [4,8,5]0
(4 (8 (5)))
foldr (-) 1 [4,8,5]4 - (foldr (-) 1 [8,5])4 - (8 - foldr (-) 1 [5])4 - (8 - (5 - foldr (-) 1 []))4 - (8 - (5 - 1))4 - (8 - 4)4 - 40
fold – Reduction operatorr - right hand side first
(4 (8 (5)))(4 (8 (5)))(4 (8 (5)))
Haskell Overview 12 Young Won Lim7/27/16
Simple List Functions – foldl function
foldl (-) 1 [4,8,5]-16
(((4) 8) 5)
foldl (-) 1 [4,8,5](foldl (-) 1 [4,8]) - 5((foldl (-) 1 [4]) - 8) – 5((1 – 4) – 8) – 5((-3) – 8) – 5-11 -5 -16
fold – Reduction operatorl - left hand side first
(((4) 8) 5)(((4) 8) 5)(((4) 8) 5)
Haskell Overview 13 Young Won Lim7/27/16
Simple List Functions – zip and unzip functions
zip [1, 2, 3] [10,20,30]
[(1,10),(2,20),(3,30)]
([1, 2, 3],[10,20,30])
unzip [(1,10),(2,20),(3,30)]
Haskell Overview 14 Young Won Lim7/27/16
Simple List Functions – zip and unzip functions
zip "hello" [1,2,3,4,5][('h',1),('e',2),('l',3),('l',4),('o',5)]
unzip [('h',1),('e',2),('l',3),('l',4),('o',5)]("hello", [1,2,3,4,5])
Haskell Overview 15 Young Won Lim7/27/16
Simple List Functions – zipWith function
zipWith f [1, 2, 3] [10,20,30]
[f 1 10, f 2 20, f 3 30]
zipWith (*) [1, 2, 3] [10,20,30]
[(*) 1 10, (*) 2 20, (*) 3 30][ 1 * 10, 2 * 20, 3 * 30 ]
[10, 40, 90]
Haskell Overview 16 Young Won Lim7/27/16
Simple List Functions – myZipWith function
myZipWith :: (a -> a -> a) -> [a] -> [a] -> [a]
myZipWith _ [] _ = []myZipWith _ _ [] = []myZipWith f (a:as) (b:bs) = (f a b) : myZipWith f as bs
Haskell Overview 17 Young Won Lim7/27/16
The n-th element in a list
nthListEl L 1 = head LnthListEl L n = nthListEl (tail L) (n-1)
*Main> nthListE1 [1, 2, 3] 33*Main> nthListE1 [1, 2, 3] 22*Main> nthListE1 [1, 2, 3] 11*Main> nthListE1 [1, 2, 3, 4, 5, 6] 55*Main> nthListE1 [11, 22, 33, 44, 55, 66] 555
Haskell Overview 18 Young Won Lim7/27/16
Recursion - factorial
fact 0 = 1fact n = n * fact (n-1)
6 * fact(5)5 * fact(4)
4 * fact(3)3 * fact(2)
2 * fact(1)1 * fact(0)1 * 1
2 * 13 * 2 * 1
4 * 3 * 2 * 15 * 4 * 3 * 2 * 1
6 * 5 * 4 * 3 * 2 * 1
Haskell Overview 19 Young Won Lim7/27/16
Polymorphic Type
types that are universally quantified in some way over all types
essentially describe families of types
(forall a) [a] is the family of types consisting of,
for every type a, the type of lists of a.
● lists of integers (e.g. [1,2,3])
● lists of characters (['a','b','c'])
● lists of lists of integers, etc.
● [2,'b'] is not a valid example
https://www.haskell.org/tutorial/goodies.html
Haskell Overview 20 Young Won Lim7/27/16
User Defined Types
data Bool = True | False
data Color = Red | Green | Blue
data Point a = Pt a a
https://www.haskell.org/tutorial/goodies.html
Type Constructor Data ConstructorThe type being defined here is Bool, and it has exactly two values: True and False.
A nullary constructor:takes no arguments
A multi-constructor
A single constructorA unary constructor(one argument a)
Pt :: a -> a -> Point a
Pt 2.0 3.0 :: Point FloatPt 'a' 'b' :: Point CharPt True False :: Point Bool
Type Constructor Data Constructor
Haskell Overview 21 Young Won Lim7/27/16
Construct
(:) :: a -> [a] -> [a]Any type List of any type List of any type
takes an element and combines it with the rest of the list
[1, 2, 3]
1 : 2 : 3 : [ ]
1 : (2 : (3 : [ ])))
cons 1 (cons 2 (cons 3 Nil)))
[ ]:: [a] the empty list takes zero arguments
Haskell Overview 22 Young Won Lim7/27/16
Recursive Definition of Lists
data [a] = [ ] | a : [a]
List = [ ] | (a : List)
https://www.haskell.org/tutorial/goodies.html
Type Constructor Data Constructor
an empty list
a list with at least one element
[ ] (x:xs)
Any type is ok but The type of every element in the list must be the same
Haskell Overview 23 Young Won Lim7/27/16
Functions using the list constructor
sumList :: [Int] -> Int
sumList [] = 0
sumList (x:xs) = x + sumList xs
NthListEl’ (L, Ls) 1 = L
NthListEl’ (L, Ls) n = NthListEl’ Ls (n-1)
Haskell Overview 24 Young Won Lim7/27/16
Map Function using the list constructor
map :: (a -> b) -> [a] -> [b]
map f [] = []
map f (x:xs) = f x : map f xs
List of a type
List of b type
Function param: a typereturn: b type
code :: String -> [Int]
code x = map ord x
code “Hugs”
[72, 117, 103, 115)
Haskell Overview 25 Young Won Lim7/27/16
Function as an argument (1)
map :: (a -> b) -> [a] -> [b]
map f [ ] = [ ]
map f (x:xs) = f x : map f xs
List of a type
List of b type
Function fparam: a typereturn: b type
Haskell Overview 26 Young Won Lim7/27/16
Function as an argument (2)
myfilter :: (a -> Bool) -> [a] -> [a]
myfilter f [ ] = [ ]
myfilter f (x:xs) = if f x then x : myfilter f xs
else myfilter f xs
Haskell Overview 27 Young Won Lim7/27/16
Solving a list of quadratic equations
roots :: (Float, Float, Float) -> (Float, Float)roots (a,b,c) = if d < 0 then error "sorry" else (x1, x2)
where x1 = e + sqrt d / (2 * a)x2 = e - sqrt d / (2 * a)d = b * b - 4 * a * ce = - b / (2 * a)
real :: (Float, Float, Float) -> Boolreal (a,b,c) = (b*b - 4*a*c) >= 0
p1 = (1.0,2.0,1.0) :: (Float, Float, Float)p2 = (1.0,1.0,1.0) :: (Float, Float, Float)ps = [p1,p2]newPs = filter real psrootsOfPs = map roots newPs
Haskell Overview 28 Young Won Lim7/27/16
Tuple Functions
Extract the first component of a pair.
Extract the second component of a pair.
curry converts an uncurried function to a curried function.
uncurry converts a curried function to a function on pairs.
fst :: (a, b) -> a
snd :: (a, b) -> b
curry :: ((a, b) -> c) -> a -> b -> c
uncurry :: (a -> b -> c) -> (a, b) -> c
swap :: (a, b) -> (b, a)
Swap the components of a pair.
Haskell Overview 29 Young Won Lim7/27/16
Gauss Area Formula
https://en.wikipedia.org/wiki/Shoelace_formula
Haskell Overview 30 Young Won Lim7/27/16
Shoelace Area Formula
https://en.wikipedia.org/wiki/Shoelace_formula
2 A =∑i=1
n
(xi − x i+1)( yi + y i+1)x1
x2
x3
⋮
xn
y1
y2
y3
⋮
yn
x1 y1
x1
x2
x3
⋮
xn
y1
y2
y3
⋮
yn
x1 y1
12
Shoelace Area Formula
=∑i=1
n
(x i y i − x i+1 y i+1 − x i+1 y i + x i y i+1)
Another Form
Haskell Overview 31 Young Won Lim7/27/16
Shoelace Area Formula
https://en.wikipedia.org/wiki/Shoelace_formula
2 A =∑i=1
n
(xi − x i+1)( yi + y i+1)
=∑i=1
n
(x i y i − x i+1 y i+1 − x i+1 y i + x i y i+1)
=∑i=1
n
(x i y i+1 − x i+1 y i)
(x1 y1 + x2 y2 + ⋯+ xn yn)
− (x2 y2 + ⋯+ xn yn + x1 y1)
Haskell Overview 32 Young Won Lim7/27/16
Simple Verification of Gauss Area Formula
https://en.wikipedia.org/wiki/Shoelace_formula(x2−x1) y2 (x3−x 2) y2
(x2−x1) y1 (x3−x 2) y3
(x1−x5) y1 (x5−x4) y4 (x4−x3) y4
(x1−x5) y5 (x5−x4) y5 (x4−x3) y3
++
++ − − −
− − −
Haskell Overview 33 Young Won Lim7/27/16
Making Lists
p = [(100.0,100.0),(100.0,200.0),(200.0,200.0),(200.0,100.0)] :: [(Float,Float)]
p = [ (x1, y1), (x2, y2), (x3, y3), (x4, y4) ] :: [ (Float, Float) ]
list1 = map fst plist2 = tail list1 ++ [head list1]list3 = map snd plist4 = tail list3 ++ [head list3]
A =12|∑i=1
n
(x i − x i+1)( y i + y i+1)|
list1 → [x1, x2, x3, x4]list2 → [x2, x3, x4, x1]list3 → [y1, y2, y3, y4]list4 → [y2, y3, y4, y1]
ps
Haskell Overview 34 Young Won Lim7/27/16
Calculating area
zipWith (–) list1 list2 → [x1–x2, x2–x3, x3–x4, x4–x1]
zipWith (+) list3 list4 → [y1+y2, y2+y3, y3+y4, y4+y1]
12|∑
i=1
n
(xi − x i+1)( y i + yi+1)|
zipWith (*) zipWith (–) list1 list2 zipWith (+) list3 list4
[(x1–x2)(y1+y2), (x2–x3)(y2+y3), (x3–x4)(y3+y4), (x4–x1)(y4+y1)]
→
foldl (+) 0 zipWith (*)
zipWith (–) list1 list2 zipWith (+) list3 list4
list1 → [x1, x2, x3, x4]list2 → [x2, x3, x4, x1]list3 → [y1, y2, y3, y4]list4 → [y2, y3, y4, y1]
→ ∑i=1
n
(x i − x i+1)( y i + y i+1)
Haskell Overview 35 Young Won Lim7/27/16
Area function
area :: [(Float,Float)] -> Float
area [] = error "not a polygon"area [x] = error "points do not have an area"area [x,y] = error "lines do not have an area"
area ps = abs ((foldl (+) 0.0 parts) / 2) whereparts = zipWith (*) (zipWith (-) l1 l2) (zipWith (+) l3 l4)l1 = map fst psl2 = tail l1 ++ [head l1]l3 = map snd psl4 = tail l3 ++ [head l3]
list1 → [x1, x2, x3, x4]list2 → [x2, x3, x4, x1]list3 → [y1, y2, y3, y4]list4 → [y2, y3, y4, y1]
Haskell Overview 36 Young Won Lim7/27/16
Counting functions
l1 [] = 0l1 (x:xs) = 1 + l1 xs
l2 xs = if xs == [] then 0 else 1 + l2 (tail xs)
l3 xs | xs == [] = 0 | otherwise = 1 + l3 (tail xs)
l4 = sum . map (const 1)
l5 xs = foldl inc 0 xs where inc x _ = x+1
l6 = foldl’ (\n _ -> n + 1) 0
Pattern Matching
if-then-else
guard notation
replace and sum
local function, local counter
lambda expression
Haskell Overview 37 Young Won Lim7/27/16
Guard Notation
sign x | x > 0 = 1 | x == 0 = 0| x < 0 = -1
if (x > 0) sign = +1;else if (x == 0) sign = 0;else sign= -1
https://www.haskell.org/tutorial/patterns.html
Haskell Overview 38 Young Won Lim7/27/16
Anonymous Function
https://www.haskell.org/tutorial/patterns.html
λ x → x2
\ x -> x*x
In Lambda CalculusLambda ExpressionLambda AbstractionAnonymous Function
Input
Prompt> (\x -> x + 1) 45 :: Integer
Prompt> (\x y -> x + y) 3 58 :: Integer
addOne = \x -> x + 1
Haskell Overview 39 Young Won Lim7/27/16
Naming a Lambda Expression
inc x = x + 1
add x y = x + y
https://www.haskell.org/tutorial/patterns.html
inc = \x -> x + 1
add = \x y -> x + y
Input
Lambda Expression
Haskell Overview 40 Young Won Lim7/27/16
Lambda Calculus
The lambda calculus consists of a language of lambda terms, which is defined by a certain formal syntax, and a set of transformation rules, which allow manipulation of the lambda terms.
These transformation rules can be viewed as an equational theory or as an operational definition.
All functions in the lambda calculus are anonymous functions, having no names.
They only accept one input variable, with currying used to implement functions with several variables.
Haskell Overview 41 Young Won Lim7/27/16
Composite Function
(.) :: (b -> c) -> (a -> b) -> (a -> c)
f . g = \ x -> f (g x)
https://www.haskell.org/tutorial/patterns.html
f g f(g(x))
Haskell Overview 42 Young Won Lim7/27/16
Local Variables
lend amt bal = let reserve = 100 newBal = bal - amt in if bal < reserve then Nothing else Just newBal
lend2 amt bal = if amt < reserve * 0.5 then Just newBal else Nothing where reserve = 100 newBal = bal - amt
http://book.realworldhaskell.org/read/defining-types-streamlining-functions.html
Haskell Overview 43 Young Won Lim7/27/16
Local Function
pluralise :: String -> [Int] -> [String]pluralise word counts = map plural counts where plural 0 = "no " ++ word ++ "s" plural 1 = "one " ++ word plural n = show n ++ " " ++ word ++ "s"
http://book.realworldhaskell.org/read/defining-types-streamlining-functions.html
Haskell Overview 44 Young Won Lim7/27/16
Local Function
roots :: (Float, Float, Float) -> (Float, Float)
type PolyT = (Float, Float, Float)type RootsT = (Float, Float)
roots :: PolyT -> RootsT
http://book.realworldhaskell.org/read/defining-types-streamlining-functions.html
typedef
Young Won Lim7/27/16
References
[1] ftp://ftp.geoinfo.tuwien.ac.at/navratil/HaskellTutorial.pdf[2] https://www.umiacs.umd.edu/~hal/docs/daume02yaht.pdf