functional programming - lists

46
Functional Programming Lists H. Turgut Uyar 2013-2015

Upload: turgut-uyar

Post on 25-May-2015

494 views

Category:

Education


1 download

DESCRIPTION

Lists in functional programming. List operators, list comprehension. List functions in the Haskell prelude.

TRANSCRIPT

Page 1: Functional Programming - Lists

Functional ProgrammingLists

H. Turgut Uyar

2013-2015

Page 2: Functional Programming - Lists

License

© 2013-2015 H. Turgut Uyar

You are free to:

Share – copy and redistribute the material in any medium or format

Adapt – remix, transform, and build upon the material

Under the following terms:

Attribution – You must give appropriate credit, provide a link to the license, andindicate if changes were made.

NonCommercial – You may not use the material for commercial purposes.

ShareAlike – If you remix, transform, or build upon the material, you mustdistribute your contributions under the same license as the original.

For more information:https://creativecommons.org/licenses/by-nc-sa/4.0/

Read the full license:

https://creativecommons.org/licenses/by-nc-sa/4.0/legalcode

Page 3: Functional Programming - Lists

Topics

1 ListsOperatorsRangesList Comprehension

2 Prelude FunctionsBasic FunctionsZip - UnzipExamples

Page 4: Functional Programming - Lists

Topics

1 ListsOperatorsRangesList Comprehension

2 Prelude FunctionsBasic FunctionsZip - UnzipExamples

Page 5: Functional Programming - Lists

Indexing

index operator: !!"word" !! 2 ~> ’r’

note that this is the same as:(!!) "word" 2

(!!) :: [a] -> Int -> a(!!) [] _ = error "no such element"(!!) (x:xs) 0 = x(!!) (x:xs) n = (!!) xs (n - 1)

Page 6: Functional Programming - Lists

Indexing

use the infix operator notation

(!!) :: [a] -> Int -> a[] !! _ = error "no such element"(x:xs) !! 0 = x(x:xs) !! n = xs !! (n - 1)

Page 7: Functional Programming - Lists

Appending Lists

append operator: ++"word" ++ "smith" ~> "wordsmith"

(++) :: [a] -> [a] -> [a][] ++ ys = ys(x:xs) ++ ys = x : (xs ++ ys)

Page 8: Functional Programming - Lists

Topics

1 ListsOperatorsRangesList Comprehension

2 Prelude FunctionsBasic FunctionsZip - UnzipExamples

Page 9: Functional Programming - Lists

Range Expressions

[n .. m]: range with increment 1

[n, p .. m]: range with increment p - n

examples

[2 .. 7] -- [2, 3, 4, 5, 6, 7][3.1 .. 7.0] -- [3.1, 4.1, 5.1, 6.1, 7.1][’a’ .. ’m’] -- "abcdefghijklm"

[7, 6 .. 3] -- [7, 6, 5, 4, 3][0.0, 0.3 .. 1.0] -- [0.0, 0.3, 0.6, 0.8999999999999999][’a’, ’c’ .. ’n’] -- "acegikm"

Page 10: Functional Programming - Lists

Constructing Ranges

construct a list from a lower limit to an upper limit

countUp :: Integer -> Integer -> [Integer]countUp lower upper| lower > upper = []| otherwise = lower : countUp (lower + 1) upper

exercise: countDown (tail recursive)

Page 11: Functional Programming - Lists

Constructing Ranges

construct a list from a lower limit to an upper limit

countUp :: Integer -> Integer -> [Integer]countUp lower upper| lower > upper = []| otherwise = lower : countUp (lower + 1) upper

exercise: countDown (tail recursive)

Page 12: Functional Programming - Lists

Topics

1 ListsOperatorsRangesList Comprehension

2 Prelude FunctionsBasic FunctionsZip - UnzipExamples

Page 13: Functional Programming - Lists

List Comprehension

describe a list in terms of the elements of another list

generate, test, transform

[e | v1 <- l1, v2 <- l2, ..., p1, p2, ...]

Page 14: Functional Programming - Lists

List Comprehension Examples

[2 * n | n <- [2, 4, 7]] -- [4, 8, 14][even n | n <- [2, 4, 7]] -- [True, True, False]

[2 * n | n <- [2, 4, 7], even n, n > 3] -- [8]

[m + n | (m, n) <- [(2, 3), (2, 1), (7, 8)]]-- [5, 3, 15]

[(x, y, z) | x <- [1 .. 5], y <- [1 .. 5],z <- [1 .. 5],x*x + y*y == z*z]

Page 15: Functional Programming - Lists

List Comprehension Examples

Python

[2 * n for n in [2, 4, 7]][even(n) for n in [2, 4, 7]]

[2 * n for n in [2, 4, 7] if even(n) and (n > 3)]

[m + n for (m, n) in [(2, 3), (2, 1), (7, 8)]]

[(x, y, z) for x in range(1, 6)for y in range(1, 6)for z in range(1, 6)if x * x + y * y == z * z]

Page 16: Functional Programming - Lists

List Comprehension Example

quick sort

qSort :: [Integer] -> [Integer]qSort [] = []qSort (x:xs) =

qSort smaller ++ [x] ++ qSort largerwheresmaller = [a | a <- xs, a <= x]larger = [b | b <- xs, b > x]

Page 17: Functional Programming - Lists

Topics

1 ListsOperatorsRangesList Comprehension

2 Prelude FunctionsBasic FunctionsZip - UnzipExamples

Page 18: Functional Programming - Lists

Membership Check

check whether an element is a member of a listelem ’r’ "word" ~> Trueelem ’x’ "word" ~> False

elem :: Char -> [Char] -> Boolelem _ [] = Falseelem x (c:cs) = if x == c then True else elem x cs

exercise: make a list of n copies of an itemreplicate 3 ’c’ ~> "ccc"

Page 19: Functional Programming - Lists

Membership Check

check whether an element is a member of a listelem ’r’ "word" ~> Trueelem ’x’ "word" ~> False

elem :: Char -> [Char] -> Boolelem _ [] = Falseelem x (c:cs) = if x == c then True else elem x cs

exercise: make a list of n copies of an itemreplicate 3 ’c’ ~> "ccc"

Page 20: Functional Programming - Lists

Last Element

get the last element of a listlast "word" ~> ’d’

last :: [a] -> alast [] = error "empty list"last [x] = xlast (x:xs) = last xs

exercise: get all elements but the last of a listinit "word" ~> "wor"

Page 21: Functional Programming - Lists

Last Element

get the last element of a listlast "word" ~> ’d’

last :: [a] -> alast [] = error "empty list"last [x] = xlast (x:xs) = last xs

exercise: get all elements but the last of a listinit "word" ~> "wor"

Page 22: Functional Programming - Lists

Split

take n elements from the front of a listtake 3 "Peccary" ~> "Pec"

take :: Int -> [a] -> [a]take 0 _ = []take _ [] = []take n (x:xs) = x : take (n - 1) xs

exercise: drop n elements from the front of a listdrop 3 "Peccary" ~> "cary"

exercise: split a list at a given positionsplitAt 3 "Peccary" ~> ("Pec", "cary")

Page 23: Functional Programming - Lists

Split

take n elements from the front of a listtake 3 "Peccary" ~> "Pec"

take :: Int -> [a] -> [a]take 0 _ = []take _ [] = []take n (x:xs) = x : take (n - 1) xs

exercise: drop n elements from the front of a listdrop 3 "Peccary" ~> "cary"

exercise: split a list at a given positionsplitAt 3 "Peccary" ~> ("Pec", "cary")

Page 24: Functional Programming - Lists

Reverse

reverse a listreverse "word" ~> "drow"

reverse :: [a] -> [a]reverse [] = []reverse (x:xs) = (reverse xs) ++ [x]

Page 25: Functional Programming - Lists

Concatenate

convert a list of lists of items into a list of itemsconcat [[2, 3], [], [4] ~> [2, 3, 4]

concat :: [[a]] -> [a]concat [] = []concat (xs:xss) = xs ++ concat xss

exercise: write concat using list comprehension

Page 26: Functional Programming - Lists

Concatenate

convert a list of lists of items into a list of itemsconcat [[2, 3], [], [4] ~> [2, 3, 4]

concat :: [[a]] -> [a]concat [] = []concat (xs:xss) = xs ++ concat xss

exercise: write concat using list comprehension

Page 27: Functional Programming - Lists

Topics

1 ListsOperatorsRangesList Comprehension

2 Prelude FunctionsBasic FunctionsZip - UnzipExamples

Page 28: Functional Programming - Lists

Zip

convert two lists into a list of pairszip [1, 2] "ab" ~> [(1, ’a’), (2, ’b’)]

zip :: [a] -> [b] -> [(a, b)]zip [] [] = []zip (x:xs) (y:ys) = (x, y) : zip xs ys

not all cases are covered:zip [1, 2] "abc" ~> [(1, ’a’), (2, ’b’)]

Page 29: Functional Programming - Lists

Zip

convert two lists into a list of pairszip [1, 2] "ab" ~> [(1, ’a’), (2, ’b’)]

zip :: [a] -> [b] -> [(a, b)]zip [] [] = []zip (x:xs) (y:ys) = (x, y) : zip xs ys

not all cases are covered:zip [1, 2] "abc" ~> [(1, ’a’), (2, ’b’)]

Page 30: Functional Programming - Lists

Zip

zip :: [a] -> [b] -> [(a, b)]zip (x:xs) (y:ys) = (x, y) : zip xs yszip _ _ = []

exercise: convert three lists into a list of tripleszip3 [1, 2] "abc" [7, 4]

~> [(1, ’a’, 7), (2, ’b’, 4)]

Page 31: Functional Programming - Lists

Zip

zip :: [a] -> [b] -> [(a, b)]zip (x:xs) (y:ys) = (x, y) : zip xs yszip _ _ = []

exercise: convert three lists into a list of tripleszip3 [1, 2] "abc" [7, 4]

~> [(1, ’a’, 7), (2, ’b’, 4)]

Page 32: Functional Programming - Lists

Unzip

convert a list of pairs into a pair of listsunzip [(1, ’a’), (2, ’b’)] ~> ([1, 2], "ab")

unzip :: [(a, b)] -> ([a], [b])unzip [] = ([], [])unzip ((x, y):xys) = (x : xs, y : ys)where(xs, ys) = unzip xys

exercise: convert a list of triples into three listsunzip3 [(1, ’a’, 7), (2, ’b’, 4)]

~> ([1, 2], "ab", [7, 4])

Page 33: Functional Programming - Lists

Unzip

convert a list of pairs into a pair of listsunzip [(1, ’a’), (2, ’b’)] ~> ([1, 2], "ab")

unzip :: [(a, b)] -> ([a], [b])unzip [] = ([], [])unzip ((x, y):xys) = (x : xs, y : ys)where(xs, ys) = unzip xys

exercise: convert a list of triples into three listsunzip3 [(1, ’a’, 7), (2, ’b’, 4)]

~> ([1, 2], "ab", [7, 4])

Page 34: Functional Programming - Lists

Topics

1 ListsOperatorsRangesList Comprehension

2 Prelude FunctionsBasic FunctionsZip - UnzipExamples

Page 35: Functional Programming - Lists

List Maximum

maximum of a list

maxList :: [Integer] -> IntegermaxList [] = error "empty list"maxList [x] = xmaxList (x:xs)| x > maxList xs = x| otherwise = maxList xs

what if called as:maxList [30, 29 .. 1]maxList [1 .. 30]

Page 36: Functional Programming - Lists

List Maximum

maximum of a list

maxList :: [Integer] -> IntegermaxList [] = error "empty list"maxList [x] = xmaxList (x:xs)| x > maxList xs = x| otherwise = maxList xs

what if called as:maxList [30, 29 .. 1]maxList [1 .. 30]

Page 37: Functional Programming - Lists

List Maximum

maximum of a list

maxList :: [Integer] -> IntegermaxList [] = error "empty list"maxList [x] = xmaxList (x:xs)| x > maxTail = x| otherwise = maxTailwheremaxTail = maxList xs

Page 38: Functional Programming - Lists

Merging Lists

merge two ordered lists

merge :: [Integer] -> [Integer] -> [Integer]merge xs [] = xsmerge [] ys = ysmerge (x:xs) (y:ys)| x <= y = x : merge xs (y : ys)| otherwise = y : merge (x : xs) ys

reconstructing original lists not necessary: @

Page 39: Functional Programming - Lists

Merging Lists

merge two ordered lists

merge :: [Integer] -> [Integer] -> [Integer]merge xs [] = xsmerge [] ys = ysmerge xs@(x’:xs’) ys@(y’:ys’)| x’ <= y’ = x’ : merge xs’ ys| otherwise = y’ : merge xs ys’

exercise: check whether an integer list is in non-decreasing order

Page 40: Functional Programming - Lists

Merging Lists

merge two ordered lists

merge :: [Integer] -> [Integer] -> [Integer]merge xs [] = xsmerge [] ys = ysmerge xs@(x’:xs’) ys@(y’:ys’)| x’ <= y’ = x’ : merge xs’ ys| otherwise = y’ : merge xs ys’

exercise: check whether an integer list is in non-decreasing order

Page 41: Functional Programming - Lists

Roman Numeral Conversion

convert an integer to Roman numeralsadapted from the book “Dive into Python” by Mark Pilgrim:http://www.diveintopython.net/

romanNumerals =[("M", 1000), ("CM", 900), ("D", 500), ("CD", 400),("C", 100), ("XC", 90), ("L", 50), ("XL", 40),("X", 10), ("IX", 9), ("V", 5), ("IV", 4),("I", 1)]

Page 42: Functional Programming - Lists

Roman Numeral Conversion

Python

def toRoman(n):result = ""for numeral, integer in romanNumerals:

while n >= integer:result += numeraln -= integer

return result

Page 43: Functional Programming - Lists

Roman Numeral Conversion

toRoman :: Integer -> StringtoRoman n = tR n romanNumeralswheretR :: Integer -> [(String, Integer)] -> StringtR n [] = ""tR n xs@((s, k):xs’)| n >= k = s ++ tR (n - k) xs| otherwise = tR n xs’

exercise: convert a Roman numeral string into an integer

Page 44: Functional Programming - Lists

Roman Numeral Conversion

toRoman :: Integer -> StringtoRoman n = tR n romanNumeralswheretR :: Integer -> [(String, Integer)] -> StringtR n [] = ""tR n xs@((s, k):xs’)| n >= k = s ++ tR (n - k) xs| otherwise = tR n xs’

exercise: convert a Roman numeral string into an integer

Page 45: Functional Programming - Lists

Roman Numeral Conversion

Python

def fromRoman(s):result = 0index = 0for numeral, integer in romanNumerals:

while s[index : index+len(numeral)] == numeral:result += integerindex += len(numeral)

return result

Page 46: Functional Programming - Lists

References

Required Reading: ThompsonChapter 6: Programming with lists

Chapter 7: Defining functions over lists