Functional Programming - Exercises

Size: px
Start display at page:

Download "Functional Programming - Exercises"

Transcription

1 Functional Programming - Exercises DCC-FCUP 2018

2 Defining simple functions (Lab. classes 1 and 2) 1. Consider the following function denitions: incr x = x + 1 square x = x x double x = x + x avg x y = (x + y)/2 Performing step-by-step reduction, determine the value of the following expressions: (a) incr (square 5) (b) square (incr 5) (c) avg (double 3) (incr 5) 2. In a triangle the following conditions is always true: the measure any side is less than the sum of the other two sides. Complete the denition of a function triangle a b c = that veries this condition (the result must be a boolean value). 3. Write in Haskell a function that calculates the area A of a triangle with sides a, b, c using the Heron formula: A = p s(s a)(s b)(s c), where s is half of the triangle's perimeter. 4. Using the functions from the Prelude presented in the rst lecture, write a function halfs that divides a list of even length in two list with half of its length. For example: halfs [1, 2, 3, 4, 5, 6, 7, 8] = ([1, 2, 3, 4], [5, 6, 7, 8]). Check what happens if the list has odd length. 5. (a) Show that the function last (which selects the last element of a list), can be written by composing functions from the Prelude (presented in the rst lecture). Can you give two dierent denitions? (b) Show that the function init (which removes the last element of a list) can be dened analogously in two dierent ways. 6. (a) Write a function binom with two arguments that calculates the binomial coecient : n n! = k k!(n k)! Suggestion: you can express n! as product [1..n]. (b) For all the lists of numbers xs and ys, we have that product (xs +ys) = product xs product ys. Use this property to write a more ecient denition, by eliminating the common factors between the numerator and denominator. 7. Consider the following denitions of functions max and min from the Prelude that calculate the maximum and minimum between two numbers, respectively: max x y = if x y then x else y min x y = if x y then x else y (a) Using nested conditional expressions, write denitions of two functions max3 and min3 to determine, respectively, the maximum and minimum of three numbers. 2

3 (b) Rewrite the functions max3 and min3 using only the composition of max and min (i.e. without conditionals or guards). 8. Implement in Haskell the following functions: (a) maxoccurs :: Integer Integer (Integer, Integer) that returns the maximum between two integers and the number of times it occurs. (b) ordertriple :: (Integer, Integer, Integer) > (Integer, Integer, Integer) that orders the triple in ascending order. 9. Write two denitions, respectively using conditional expressions and guards, of the function classify :: Int String that associates a qualitative classication to a mark from 0 to 20: 9 failed 10{12 sucient 13{15 good 16{18 very good 19{20 very good with distinction 10. Write a denition of the logic function exclusive-or xor :: Bool Bool Bool using multiple equations with patterns. 11. We want to implement a function safetail :: [a] [a] that extends the function tail from the Prelude, in order to return the empty list when the argument is the empty list (instead of producing an error). Write three dierent denitions using conditionals, equations with guards and patterns. 12. Write two denitions of the function short :: [a] Bool to test if a list has zero, one or two elements, using: (a) the function length from Prelude; (b) multiple equations and patterns. 13. Dene a function textual :: Int String to convert a positive number up to a million to the designation in English. Some examples: textual 21 = \Twenty one" textual 1234 = \one thousand two hundred and thirty four" textual = \one hundred and twenty three thousand four hundred and fty six" Suggestion: Start by dening auxiliary functions to convert to text numbers inferior to 100 and Types and classes (Lab. class 2) 14. Indicate admissible types for the following values. (a) [ 0 a 0 0, b 0 0, c 0 ] (b) ( 0 a 0 0, b 0 0, c 0 ) (c) [(False, ), (True, )] (d) ([False, True], [ 0 0 0, ]) 3

4 (e) [tail, init, reverse] (f) [id, not] 15. Indicate admissible types for f and g such that: 1. f (2,5) has type Int; 2. f (g 5) has type Int; 3. (f g) 5 has type Int; 4. f g [1,2,3] has type [Int]; 5. f (2,5) has type [Int -> Int]. 16. What is the most general type for f and g such that head (f g) 5 has type [Int]. 17. Indicate the most general type for the following denitions; in case of operations with overloading, please include the necessary class restrictions. (a) second xs = head (tail xs) (b) swap (x, y) = (y, x) (c) pair x y = (x, y) (d) double x = 2 x (e) half x = x/2 (f) minuscule x = x 0 a 0 && x 0 z 0 (g) interval x a b = x a && x b (h) palindrome xs = reverse xs == xs (i) twice f x = f (f x) 18. Indicate examples of admissible types and most general types for each of the denitions in exercises 1 and 2. Only include class restrictions, when absolutely necessary. 19. Give examples of functions, with denitions compatible with the following types: 1. Int -> (Int -> Int) -> Int 2. Char -> Bool -> Bool 3. (Char -> Char -> Int) -> Char -> Int 4. Eq a => a -> [a] -> Bool 5. Eq a => a -> [a] -> [a] 6. Ord a => a -> a -> a 20. State if the function f :: (a,[a]) -> Bool can be applied to the arguments (2, [3]), (2, []) e (2, [True]). In armative case, what are the types of the result? 21. Repeat the last exercise for the function f :: (a,[a]) -> a 4

5 List comprehensions (Lab. class 3) 22. Using a list comprehension, write an expression to calculate the sum of the squares of integers from 1 to The mathematical constant π can be approximated using series expansion(i.e. innite sums), such as: π 4 = ( 1)n 2n (a) Write a function aprox :: Int Double to approximate π bu summing n parcels of the above series (where n is the argument of the function). (b) The previous series converges very slowly, therefore one needs several terms to get a good approximation; write another function aprox 0 using the following expansion for π 2 : π 2 12 = ( 1)k (k + 1) 2 + Compare the results obtained by summing 10, 100 and 1000 terms with the approximation pi from the Prelude. 24. Dene a function divprop :: Int [Int] using a list comprehension to calculate the list of proper divisors of a positive integer (i.e. divisor inferior to the given number). For example: divprop 10 = [1, 2, 5]. 25. A positive integer n is called perfect if it equal to the sum of its divisors (excluding n itself). Dene a function perfects :: Int [Int] that calculates the list of all the perfect numbers up to a limit given as argument. Example: perfects 500 = [6, 28, 496]. Suggestion: use the solution from exercise Dene a function prime :: Int Bool that test for primality: n is a prime if it has exactly two divisors, 1 and n. Suggestion: use the function for exercise 24 to get the list of proper divisors. 27. Using a function binom that calculates the binomial coecient (see exercise 6), write a function pascal :: Int [[Int]] that given an n, calculates the rst n lines of the Pascal triangle. 28. Write a function dotprod :: [Float] [Float] Float that calculates the internal product of two vectors (represented as lists): dotprod [x 1,..., x n ] [y 1,..., y n ] = x 1 y x n y n = n i=1 x i y i Suggestion: use the function zip :: [a] [b] [(a, b)] from Prelude to pair the two lists. 29. A triple (x, y, z) of positive integer is called pitagorical if x 2 +y 2 = z 2. Dene the function pitagorical :: Int [(Int, Int, Int)] that calculates all the pitagorical triples whose components are smaller than the argument. For example: pitagorical 10 = [(3, 4, 5), (4, 3, 5), (6, 8, 10), (8, 6, 10)]. Recursive Definitions and List Processing (Lab. classes 4 and 5) 30. Dene in Haskell: (a) the function factorial (recursively). 5

6 (b) the function rangeproduct that given two naturals n and m, calculates (c) the function factorial using rangeproduct. m (m + 1)... (n 1) n 31. Using addition, dene recursively the multiplication of two natural numbers. 32. The integer square root of a positive integer n is the greater integer whose square is less or equal than n. For example, for 15 and 16, the results are, respectively 3 and 4. Dene this function in Haskell. 33. Given a function f :: Integer > Integer and a natural number n dene a function that returns the maximum of f 0, f 1,..., f n. 34. Dene a function that given as arguments a function f :: Integer > Integer and a natural n returns True if any of the values in f 0, f 1,..., f n is equal to zero and False otherwise. 35. Dene a function that given as arguments a function f :: Integer > Integer and a natural n returns (f 0) + (f 1) (f n). 36. Dene a function in Haskell that calculates the greater common divisor between two positive integers. 37. Dene a function in Haskell that given n calculates 2 n. 38. Without looking at the denitions in Haskell Prelude, write recursive denitions for the following functions: (a) and :: [Bool] Bool (b) or :: [Bool] Bool test if all the values are True; test if any value is True; (c) concat :: [[a]] [a] concatenate a list of lists ; (d) replicate :: Int a [a] (e) (!!) :: [a] Int a (f) elem :: Eq a a [a] Bool produce a list with n equal elements; select the n-th element of a list; test if a value occurs in a list. 39. Show that the functions from Prelude concat, replicate e (!!) can also be dened without recursion using list comprehension. 40. Dene a function strong :: String Bool to verify if a password given as a string of characters is \strong", that is: it has at least 8 characters and at least an upper and a lower case letter and a digit. Suggestion: use the function or :: [Bool] Bool and list comprehension. 41. Function nub :: Eq a [a] [a] from module Data.List eliminates repeated occurrences of elements in a list. For example: nub \banana" = \ban". Write a recursive denition for this function. Suggestion: use a list comprehension with a guard to eliminate elements in a list. 42. Write a denition of function intersperse :: a [a] [a] from module Data.List which inserts a values between the elements of a list. Example: intersperse '-' \banana" = \b-a-n-a-n-a". 43. Sorting of lists using the insertion sort method. 6

7 (a) Write a recursive denition of function insert :: Ord a a [a] [a] to insert an element in an ordered list in a way that the list is kept ordered. Example: insert 2 [0, 1, 3, 5] = [0, 1, 2, 3, 5]. (b) Using the function insert, write a recursive denition of function isort :: Ord a [a] [a] which implements the insertion sort method: the empty list is already sorted; to sort a non-empty list, recursively sort the tail of the list and insert the head in the correct position. 44. Sorting of lists using the selection sort method. (a) Write a recursive denition of the function minimum :: Ord a [a] a from Prelude that calculates the minimum element of a non-empty list. Example: minimum [5, 1, 2, 1, 3] = 1. (b) Write a recursive denition of the function delete :: Eq a a [a] [a] from the library List that removes the rst occurrence of a value from a list. Example: delete 1 [5, 1, 2, 1, 3] = [5, 2, 1, 3]. (c) Using the previous functions, write a denition of the function ssort :: Ord a [a] [a] that implements the selection sort method : the empty list is already sorted; to sort a non-empty list, we place in the head the minimum element m and recursively sort the tail without the element m. 45. Sorting lists using the merge sort method. (a) Write a recursive denition of the function merge :: Ord a [a] [a] [a] to merge two ordered lists into one, keeping the ordering. Example: merge [3, 5, 7] [1, 2, 4, 6] = [1, 2, 3, 4, 5, 6, 7]. (b) Using the function merge, write a recursive denition of the function msort :: Ord a [a] [a] that implements the merge sort method: an empty or singleton list is already sorted; to sort a list with two or more elements, split the list in two halfs, recursively sort the two halfs and merge the resulting lists using merge. Suggestion: start by dening a function halfs :: [a] ([a], [a]) to split a list in two halfs. 46. Write a denition of functionbits :: Int [[Bool]] that obtains all the sequences of boolean of a given size. Example: bits 2 = [[False,False],[True,False],[False,True],[True,True]]; note that the order of the sequence is not important. Suggestion: try to express the function recursively over the length. 47. Write a function permutations :: [a] [[a]] to obtain the list of all the permutations of the elements in a list. Therefore, if xs has length n, then permutations xs has length n!. Example: permutations [1, 2, 3] = [[1, 2, 3], [2, 1, 3], [2, 3, 1], [1, 3, 2], [3, 1, 2], [3, 2, 1]]; note that the order in which the permutations appear is not important. Higher-order functions (Lab. classes 6 and 7) 48. Show how the list comprehension [f x x xs, p x] can be written as a combination of higher-order functions map and lter. 7

8 49. Without looking at the Haskell specication, write non-recursive denitions of the following functions from Prelude: (a) ( +) :: [a] [a] [a], using foldr; (b) concat :: [[a]] [a], using foldr; (c) reverse :: [a] [a], using foldr; (d) reverse :: [a] [a], using foldl; (e) elem :: Eq a a [a] Bool, using any. 50. Using foldl, dene a function dec2int :: [Int] Int that converts a list of digits into an integer. Example: dec2int [2, 3, 4, 5] = The function zipwith :: (a b c) [a] [b] [c] from Prelude is a variant of zip whose rst argument is a function used to combine each pair of elements. We can dene zipwith using list comprehension: zipwith f xs ys = [f x y (x, y) zip xs ys] Write a recursive denition of zipwith. 52. Show that one can dene the function isort :: Ord a [a] [a] to sort a list by the insertion sort method using foldr and insert. 53. Dene the function shift, which places the rst element of a list at the end. That is shift [1,2, 3] = [2, 3, 1] and shift "eat" = "ate". Using foldr and shift dene the function rotate, which produces all the possible rotations of a list. That is rotate [1, 2, 3] = [[1, 2, 3],[2, 3, 1],[3, 1, 2]]. 54. The functions foldl1 and foldr1 from Prelude are variants of foldl and foldr that are only dened for lists with at least one element (i.e. non-empty). The functions foldl1 and foldr1 have only two arguments (a folding operation and a list) and their result is given by the following equations. foldl1 ( ) [x 1,..., x n ] = (... (x 1 x 2 )...) x n foldr1 ( ) [x 1,..., x n ] = x 1 (... (x n 1 x n )...) (a) Show that you can dene the functions maximum, minimum :: Ord a [a] a from Prelude (that calculate, respectively, the maximum and minimum element in a non-empty list) using foldl1 e foldr1. (b) Show that you can dene foldl1 and foldr1 using foldl and foldr. Suggestion: use functions head, tail, last and init. 55. The function add can be dened using the functions: succ i = i + 1 pred i = i - 1 and the equations: add i 0 = i add i j = succ (add i (pred j)) 8

9 (a) Give a similar denition for mult using only add and pred. Give a denition for exp using only mult and pred. What is the next function in this sequence? (b) The function foldi on integers, can be dened in the following way: foldi :: (a -> a) -> a -> Int -> a foldi f q 0 = q foldi f q i = f (foldi f q (pred i)) Dene functions add, mult and exp in terms of foldi. (c) Dene functionsfact (factorial) and b (Fibonacci) using function foldi. 56. The higher order function until :: (a Bool) (a a) a a dened in Prelude as: until p f is the function that repeats the application of f to the argument until p is true. Using until, write a non-recursive denition of function mdc a b = if b == 0 then a else mdc b (a mod b) that calculates the greatest common divisor using Euclides algorithm. 57. The Prelude function scanl is a variant of foldl that produces a list of accumulated values: For example: scanl f z [x 1, x 2,...] = [z, f z x 1, f (f z x 1 ) x 2,...] scanl (+) 0 [1, 2, 3] = [0, 0 + 1, , ] = [0, 1, 3, 6] In particular, for nite lists xs we have last (scanl f z xs) = foldl f z xs. Write a recursive denition of scanl. Infinite lists (Lab. class 8) 58. Dene the innite lists for factorial and Fibonacci numbers, factorial = [1,1,2,6,24,120,720,...] fibonacci = [0,1,1,2,3,5,8,13,21,...] 59. Dene a function merge of two innite ordered lists, that combines the two list into one ordered list. Use the function merge with the list of all the powers of 2 and all the powers of 3. Dene a list of numbers whose unique prime factors are 2,3 and 5 (called Hamming numbers): hamming = [1,2,3,4,5,6,8,9,10,12,15,... (Suggestion: use the dened merge function). 60. Dene a function of successive sums sumss :: [Int] -> [Int] That calculates the successive sums 9

10 [0,n0,n0+n1,n0+n1+n2,... From an innite list [n0,n1,n2, In this exercise we want to dene the complete Pascal triangle as an innite list pascal :: [[Int]] of lines of the triangle. (a) Write a denition of pascal using function binom from Exercise 6. Note thatpascal!! n!! k = binom n k, for any n and k such that n > 0 and 0 k n. (b) Write another denition avoid the calculation of the factorials, using the following properties for binomial coecients: n n n + 1 n n = = 1 = + (if n > k) 0 n k + 1 k k We can make Caesar's cypher more dicult to break using a password instead of a unique shift. We start by repeating the password (for example, \LUAR") through the text; each letter from the password from `A' t `Z' corresponds to a shift from 0 to 25 (e.g., \LUAR" corresponds to shifts 11, 20, 0 and 17). A T A Q U E D E M A D R U G A D A L U A R L U A R L U A R L U A R L L N A H F Y D V X U D I F A A U L Write a function cypherkey :: String String String that implements this variant of Caesar's cypher. 63. A magic square of dimension n is a matrix n n containing integers from 1 to n 2 such that the sum of each row, column or diagonal gives the same value. The following gure represents a magic square of dimension 3, where each row, column and diagonal sum is 15. Write a program to generate magic squares Interactive programs (Lab. class 9) 64. Write a function elephants :: Int IO () such that, for example, elephants 5 prints the following verses: If 2 elephants bother a lot of people, 3 elephants bother a lot more! If 3 elephants bother a lot of people, 5 elephants bother a lot more! If 4 elephants bother a lot of people, 5 elephants bother a lot more! 10

11 Suggestion: use the function show :: Show a a String to convert an integer into a string of characters; you can also re-use the function sequence :: [IO a] IO () to execute a list of actions. 65. Write a program to reproduce the functionality of the Unix command wc: to read a le from the input and print the number of lines, words and bytes. Example: $ echo "mary had a little lamb" wc Suggestion: modify the example presented in the lecture; use the functions words and lines from the Prelude. 66. Write a program that reads lines of text from the input and prints each line inverted. 67. Write a program that codies the standard input using the 13th position Caesar cipher (see http: // Example: $ echo "mary had a little lamb"./rot13 znel unq n yvggyr ynzo 68. Write an interactive function guess :: String IO () that implements a game to guess a secret word, given by the user as argument; a second player is going to try to guess it. The program should show the word, replacing the unknown letters by dashes and asking for a new letter; then all the occurrences of the provided letter should be reveled. The game terminates when the player guesses the word; the program should then print the number of attempts. (see Figure 1) ? a -a-a-a? e Does not occur -a-a-a? b ba-a-a? n banana Guessed in 4 attempts Figure 1: Example of interaction in the guessing game. 69. The game Nim is played with ve lines of identical pieces (represented by start), and with the following initial state: 1 : 2 : 3 : 4 : 5 : 11

12 Two players will alternatively take one or more stars from one of the lines; the players that removes the last star (or group of stars) wins. Implement this game as a program in Haskell that asks for the plays and updates the board. Suggestion: represent the state of the game as a list with the number of starts in each line; the initial state will then be represented as [5, 4, 3, 2, 1]. Search trees (Lab. class 10) In the following exercises consider the denition for search trees presented in lectures: data Arv a = Vazia No a (Arv a) (Arv a) 70. Write a recursive denitions of the function sumarv :: Num a Arv a a that adds all the values of a numerical binary tree. 71. Based on the function list :: Arv a [a] presented in lectures, write the denition of function to list the elements of a search tree in descending order. 72. Write a function level :: Int Arv a [a] such that level n arv is the ordered list of the values of the tree at level n (considering that the root is at level 0). 73. Experiment on using the Haskell interpreter to calculate the height of search trees with n values. (a) using the binary partitions method e.g. build [1..n]; (b) using simple insertions, e.g. foldr insert Vazia [1..n]; (c) using AVL insertions, e.g. foldr insertavl Vazia [1..n]; Experiment with n = 10, 100 and 1000 and compare the obtained height with the theoretical lowerbound: a binary tree with n nodes has height log 2 n. 74. Write a denition of the high-order function maparv :: (a b) Arv a Arv b such that `maparv f t' applies a function f to each value in a tree t. 75. In this exercise we want to implement a variant of the function that removes a value from a simple search tree. (a) Using the function mais esq :: Arv a a presented in lectures, write a function mais dir :: Arv a a that obtains the value of a tree more to the right (i.e., the greater value). (b) Using the function dened in the previous item, write an alternative denition of the function remove :: Ord a a Arv a Arv a that uses the value more to the right of the sub-tree on the left, in case of a tree with two non-empty descendents. 76. Write a denition of the function removeavl :: Ord a a Arv a Arv a to remove the value of an AVL tree in order to keep a balanced tree. Suggestion: modify the analogous function for simple search trees. 12

13 Abstract Data Types (Lab. class 11) 77. Implement in Haskell: (a) Dene a datatype Shape to represent circles with a certain radius (Circle Float) or rectangles with sides a, b (Rectangle Float Float). (b) Dene a function to calculate the perimeter of a geometric gure of type Shape. 78. A rectangle with sides parallel to the axes is dened by the extremities bottom-left and top-right. Each of these extremities is a point dened by its coordinates. 1. Characterize the appropriate types to represent rectangles of this type. 2. Dene a function to calculate the area of a rectangle. 3. Dene a function to indicate if two give rectangles intersect (that is, if they have at least one common point). 79. Write a function parent :: String Bool that veries if a string of characters is a sequence of brackets correctly paired; for example: parent "(((()[()])))" = True parent "((]())" = False Suggestion: represent open brackets using a stack of characters `(', `[' and `{'; use the Stack module presented in lectures. 80. In the reverse polish notation (RPN ) each operator appears after the two arguments; for example, the expression is written as \42 3 * 1 +". This notation does not require brackets, or operator precedence. Write a function to calculate the value of an expression in RPN; this calculation can be done by going trough the expression a single time and using a stack to save intermediate values. (a) Write an auxiliary function calc :: Stack Float String Stack Float that implements an operation (if the 2nd argument is \+", \*", \-" or \/") or places an operand in the stack (if the 2nd argument is a numeral); the result should be the modied stack. Suggestion: use the function read :: String Float from Prelude to convert a number in text to a oating point. (b) Using the previous function and the Stack module presented in lectures, write the function calculate :: String Float that calculates the value of an RPN expression; for example: calculate \42 3 * 1 +" = 127. Suggestion: use the function words :: String [String] from Prelude to split a string of characters into words. (c) Write a program that reads an RPN expression from the standard input and calculates its value. Experiment the program with correct and incorrect expressions and interpret the results. 81. Consider a directed graph G = (V, E) dened by a nite set of nodes V and a nite set of edges E, where each edge (x, y) is a pair of nodes. 1. Dene in Haskell an appropriate structure to represent graphs. 13

14 2. Represent the graph in the following gure: Write a function that takes a directed graph and two nodes of the graph and calculates the number of distinct paths between the two nodes. We assume that the graph is acyclic. For example, for the graph in the gure above and nodes 1 and 5 the result is 4 (the corresponding paths, which you do not need to calculate are: [1,4,5], [1,2,5], [1,2,6,5] and [1,2,3,6,5]). 82. The following equations specify the operations of the abstract data type stack: pop (push x s) = s (1) top (push x s) = x (2) isempty empty = True (3) isempty (push x s) = False (4) The property (1) was veried in class; verify that the implementation using lists presented in the lectures satises the remaining properties (2){(4). 83. Based on the example for counting occurrences presented in lectures, write a program to count the occurrences of letters in a text. Suggestion: represent the occurrence counting using a dictionary Map Char Int. 84. Modify the counting example of distinct words in order to use lists without repetitions instead of Data.Set (whose implementation used balanced trees). The asymptotic analysis says that, for big sets, the search on balanced trees is more ecient than lists. Experiment to determine the size of text after which that is veried. Suggestion: use the command :set +s from the interpreter to print the time used in a computation. 85. Consider the abstract data type Set a for nite sets of values of type a with the following operations: empty :: Set a insert :: Ord a a Set a Set a member :: Ord a a Set a Bool Write an implementation of this type using binary search trees. 86. Consider the operations for union, intersection and dierence between sets; all theses operations have the same type: union, intersect, dierence :: Ord a Set a Set a Set a Add these operations to the implementation given in the previous exercise. 14

15 87. Consider the abstract data type Map k a for associating keys of type k and values of type a with the following operations: empty :: Map k a insert :: Ord k k a Map k a Map k a lookup :: Ord k k Map k a Maybe a Write an implementation of this abstract data type using binary search trees. Reasoning about programs 88. Consider the recursive denition of natural numbers and addition. data Nat = Zero Succ Nat Zero + y = y Succ x + y = Succ (x + y) Show associativity for addition: x + (y + z) = (x + y) + z for all x, y, z. Suggestion: use induction over x. 89. Using induction over the list xs, prove associativity for concatenation: (xs +ys) +zs = xs +(ys +zs). Suggestion: the proof is analogous to the one in the previous exercise. 90. Prove distributivity of reverse over +: using induction of the list xs. reverse (xs +ys) = reverse ys + reverse xs Suggestion: it is useful to use the result from the previous exercise (associativity of +). Note that the lists xs, ys appear in reversed order on the right side of equality! 91 Consider the denitions of the higher-order functions map e (composition of functions): map f [ ] = [ ] map f (x : xs) = f x : map f xs (f g) x = f (g x) Using induction over lists, show that map f (map g xs) = map (f g) xs. 92 Using the following denitions of functions take, drop :: Int [a] [a] and the canonical denition of +, show that take n xs + drop n xs = xs. take 0 xs = [ ] take n [ ] n > 0 = [ ] take n (x : xs) n > 0 = x : take (n 1) xs drop 0 xs = xs drop n [ ] n > 0 = [ ] drop n (x : xs) n > 0 = drop (n 1) xs Suggestion: use induction over n and case analysis for the list xs. 15

16 93. Using induction over lists, prove that length (map f xs) = length xs, that is, the function map preserves the length of the list. 94. Using induction over lists, prove that sum (map (1+) xs) = length xs + sum xs. Recall that the notation (1+) represents the function that adds one to a number. 95. Using induction over lists, show that for all function f and nite lists xs and ys. 96. Using induction over lists, show that map f (xs +ys) = map f xs +map f ys map f (reverse xs) = reverse (map f xs) Suggestion: use the property proved on exercise Consider the following denition of function insert :: Int [Int] [Int] that inserts a value in a list of increasing integers, maintaining the order. insert x [ ] = [x] insert x (y : ys) x y = x : y : ys insert x (y : ys) x > y = y : insert x ys Using induction over lists, prove that length (insert x xs) = 1 + length xs. 98 Consider the type declaration for a recursive type for annotated binary trees: data Arv a = Folha No a (Arv a) (Arv a) Using induction over trees, show that the number of leaves is always one plus the number of internal nodes. Suggestion: start by dening two recursive functions to calculate the number of leaves and internal nodes in a tree. 99. Consider the function to list in-order the elements of a binary tree: list :: Arv a [a] list Folha = [ ] list (No x esq dir) = list esq + [x] + list dir Use the technique to eliminate concatenations presented in lectures to derive a more ecient version of this function. Suggestion: synthesize a recursive denition of the auxiliary function listacc :: Arv a [a] [a] such that listacc t xs = list t + xs. 16

17 Supplementary exercises 100 (a) Write a function mindiv :: Int Int that calculates the smaller proper divisor of the argument (i.e. the smaller divisor greater than 1). Note that, if n = p q, then p and q are both divisors of n; thus, if p p n, then q p n thus mindiv n p n. (b) Use mindiv to dene a test for primality more ecient than the one dened on exercise 26: n is a prime if n > 1 and its smaller divisor is equal to n. 101 Caesar cipher is one of the simplest methods to encode a text: each letter is substituted by the one that is k positions down the alphabet; if it passes the letter Z, it goes back to letter A. For example, for k = 3, the applied substitution is A B C D E F G H I J K L M N O P Q R S T U V W X Y Z D E F G H I J K L M N O P Q R S T U V W X Y Z A B C and the text \ATAQUE DE MADRUGADA" is transformed into \DWDTXH GH PDGUXJDGD". Write a function cipher :: Int String String to cipher a string of characters using a given distance. Note that cipher ( n) is the inverse function of cypher n, so there is no need to dene a dierent function to decipher. 102 The eight queens puzzle consists in determine positions to place eight queens in a Chess board (with 8 8 positions) so that so that no two queens threaten each other (i.e. are in a horizontal or diagonal direct line). Write a program to search for all the solutions of the eight queen puzzle The problem of decomposing a quantity into change can be formalised in the following way: given a natural number n and a list of naturals xs, nd decompositions of n as sums of values in xs (eventually with repetitions). For example, for n = 25 and xs = [2, 5, 10] a possible decomposing is [5, 10, 10] (because 25 = ). Other possibilities are [5, 5, 5, 5, 5] or [2, 2, 2, 2, 2, 5, 10] (there are other alternatives). Write a denition of a function decompose :: Int [Int] [[Int]] such that decompose n xs nds all the alternatives for the change problem. If the problem does not have a solution the result will be the empty list Sudoku is a logic puzzle in which the purpose is to ll a 9 9 grid with integers from 1 to 9 such that each row, column and 3 3 square does not repeat numbers. The purpose is to write a program to resolve this type of puzzle; we can represent the grid as a list of rows: type Grid = [[Int]] Each element will be an integer from 1 to 9 or 0 if it is not lled yet. (a) Write a denition of function check :: Grid Bool that veries if a grid respects the constraints above. (i.e. that is, no repetitions in rows, columns and squares). (b) Write a denition of function solve :: Grid [Grid] that gets all the solutions of a Sudoku puzzle; the argument is a partially lled grid. 105 We want to solve this exercise without using words and unwords from Prelude (because words = palavras and unwords = despalavras). 17

18 (a) Write a denition of palavras :: String [String] that decomposes a line of text into words separated by one or more spaces. Example: palavras \Abra- ca- drabra!" = [\Abra-", \ca-", \dabra!"]. (b) Write a denition of despalavras :: [String] String that concatenates a list of words adding a space between each one. Note that despalavras is not the inverse function of palavras; nd a counter example for this statement. 106 Consider two series (i.e. innite sums) that converge to π: π = (5) π = (6) Write two functions calcpi1, calcpi2 :: Int -> Double that calculate and approximate value of π using the number of parcels given as argument; investigate which series converges faster to π. Suggestion: build innite lists for numerators and denominators separately and combine them using zip/zipwith. 107 Write a complete program that implements the functionality of the UNIX utility cal: printing the calendar of a year, using a 4 3 months grid; the following gure illustrates a suggestion for formatting a month: February 2016 Su Mo Tu We Th Fr Sa The height information in each sub-tree is used to re-balance the AVL trees. In this exercise the goal is to modify the implementation given in lectures to save this information instead of recalculating it every time it is used. Start by changing the type declaration for trees so that each node will have an extra argument for the height: data Arv a = Vazia No Int a (Arv a) (Arv a) Modify the functions that do rotations to correctly update the height. For the following exercises, please refer to the tautology checker presented in lectures Write the denition of a function: satises :: Prop Bool that veries if a proposition is satisable, that is, if there is an assignment of logic values to the variables that makes the proposition true Write a denition of the function equiv :: Prop Prop Bool that veries if two propositions are equivalents, that is, if they take the same truth value for all the variable assignments. Suggestion: p, q are equivalent if and only if p = q q = p is a tautology Modify the tautology checker adding a connective for equivalence between propositions. 18

19 112 Write a denition of a function showprop :: Prop String to convert a proposition in text; some examples: > showprop (Neg (Var a )) "(~a)" > showprop (Disj (Var a ) (Conj (Var a ) (Var b ))) "(a (a && b))" > showprop (Impl (Var a ) (Impl (Neg (Var a )) (Const False)) "(a -> ((~a) -> F))" 113. Modify the tautology checker to print the truth table of a proposition. More precisely, write a function table :: Prop IO () that prints the truth table of the given proposition Modify the function life presented in the lectures to verify if the board is empty, in which case the simulation terminates immediately Modify the function life presented in the lectures so that after n generations it prints the number of live cells in the board Write denitions for the following functions to transform congurations in the game of life: (a) trans :: (Int, Int) Cells Cells, such that trans (dx, dy) calculates the translation by the vector (dx, dy) of the cells in the board; (b) reh :: Cells Cells, that computes the transformation of horizontal reection (that is, with respect to the axis y); (c) rev :: Cells Cells, that computes the vertical reection (that is, with respect to the axis x); (d) rot90 :: Cells Cells, that calculates a 90 clockwise rotation; (e) Combining these transformations with primitive congurations, one can build complex congurations in a modular way. Try, for example, to simulate 100 generations of two \gliders" in a collision path: life (glider +trans (10, 0) (reh glider ))

Lecture 2: List algorithms using recursion and list comprehensions

Lecture 2: List algorithms using recursion and list comprehensions Lecture 2: List algorithms using recursion and list comprehensions Søren Haagerup Department of Mathematics and Computer Science University of Southern Denmark, Odense September 12, 2017 Expressions, patterns

More information

PROGRAMMING IN HASKELL. CS Chapter 6 - Recursive Functions

PROGRAMMING IN HASKELL. CS Chapter 6 - Recursive Functions PROGRAMMING IN HASKELL CS-205 - Chapter 6 - Recursive Functions 0 Introduction As we have seen, many functions can naturally be defined in terms of other functions. factorial :: Int Int factorial n product

More information

A general introduction to Functional Programming using Haskell

A general introduction to Functional Programming using Haskell A general introduction to Functional Programming using Haskell Matteo Rossi Dipartimento di Elettronica e Informazione Politecnico di Milano rossi@elet.polimi.it 1 Functional programming in a nutshell

More information

Lecture 4: Higher Order Functions

Lecture 4: Higher Order Functions Lecture 4: Higher Order Functions Søren Haagerup Department of Mathematics and Computer Science University of Southern Denmark, Odense September 26, 2017 HIGHER ORDER FUNCTIONS The order of a function

More information

PROGRAMMING IN HASKELL. Chapter 5 - List Comprehensions

PROGRAMMING IN HASKELL. Chapter 5 - List Comprehensions PROGRAMMING IN HASKELL Chapter 5 - List Comprehensions 0 Set Comprehensions In mathematics, the comprehension notation can be used to construct new sets from old sets. {x 2 x {1...5}} The set {1,4,9,16,25}

More information

(ii) Define a function ulh that takes a list xs, and pairs each element with all other elements in xs.

(ii) Define a function ulh that takes a list xs, and pairs each element with all other elements in xs. EXAM FUNCTIONAL PROGRAMMING Tuesday the 1st of October 2016, 08.30 h. - 10.30 h. Name: Student number: Before you begin: Do not forget to write down your name and student number above. If necessary, explain

More information

CSCE 314 TAMU Fall CSCE 314: Programming Languages Dr. Flemming Andersen. Haskell Functions

CSCE 314 TAMU Fall CSCE 314: Programming Languages Dr. Flemming Andersen. Haskell Functions 1 CSCE 314: Programming Languages Dr. Flemming Andersen Haskell Functions 2 Outline Defining Functions List Comprehensions Recursion 3 Conditional Expressions As in most programming languages, functions

More information

Introduction to Programming, Aug-Dec 2006

Introduction to Programming, Aug-Dec 2006 Introduction to Programming, Aug-Dec 2006 Lecture 3, Friday 11 Aug 2006 Lists... We can implicitly decompose a list into its head and tail by providing a pattern with two variables to denote the two components

More information

Haske k ll An introduction to Functional functional programming using Haskell Purely Lazy Example: QuickSort in Java Example: QuickSort in Haskell

Haske k ll An introduction to Functional functional programming using Haskell Purely Lazy Example: QuickSort in Java Example: QuickSort in Haskell Haskell An introduction to functional programming using Haskell Anders Møller amoeller@cs.au.dk The most popular purely functional, lazy programming language Functional programming language : a program

More information

Functional Programming in Haskell Part I : Basics

Functional Programming in Haskell Part I : Basics Functional Programming in Haskell Part I : Basics Madhavan Mukund Chennai Mathematical Institute 92 G N Chetty Rd, Chennai 600 017, India madhavan@cmi.ac.in http://www.cmi.ac.in/ madhavan Madras Christian

More information

An introduction introduction to functional functional programming programming using usin Haskell

An introduction introduction to functional functional programming programming using usin Haskell An introduction to functional programming using Haskell Anders Møller amoeller@cs.au.dkau Haskell The most popular p purely functional, lazy programming g language Functional programming language : a program

More information

Shell CSCE 314 TAMU. Functions continued

Shell CSCE 314 TAMU. Functions continued 1 CSCE 314: Programming Languages Dr. Dylan Shell Functions continued 2 Outline Defining Functions List Comprehensions Recursion 3 A Function without Recursion Many functions can naturally be defined in

More information

Standard prelude. Appendix A. A.1 Classes

Standard prelude. Appendix A. A.1 Classes Appendix A Standard prelude In this appendix we present some of the most commonly used definitions from the standard prelude. For clarity, a number of the definitions have been simplified or modified from

More information

Functional Programming in Haskell for A level teachers

Functional Programming in Haskell for A level teachers Functional Programming in Haskell for A level teachers About this document Functional Programming is now part of the A level curriculum. This document is intended to get those who already have some programming

More information

Functional Programming TDA 452, DIT 142

Functional Programming TDA 452, DIT 142 Chalmers Göteborgs Universitet 2016-04-07 Examiner: David Sands dave@chalmers.se. Answering questions on the day of the exam (at approx 15.00): Gregoire Detrez (tel: 073 55 69 550) and at other times by

More information

Higher Order Functions in Haskell

Higher Order Functions in Haskell Higher Order Functions in Haskell Evan Misshula 2018-09-10 Outline Curried Functions Curried comparison Example partial application partial application of a string function Returned functions ZipWith flip

More information

INTRODUCTION TO HASKELL

INTRODUCTION TO HASKELL INTRODUCTION TO HASKELL PRINCIPLES OF PROGRAMMING LANGUAGES Norbert Zeh Winter 2018 Dalhousie University 1/81 HASKELL: A PURELY FUNCTIONAL PROGRAMMING LANGUAGE Functions are first-class values: Can be

More information

Programming Languages 3. Definition and Proof by Induction

Programming Languages 3. Definition and Proof by Induction Programming Languages 3. Definition and Proof by Induction Shin-Cheng Mu Oct. 22, 2015 Total Functional Programming The next few lectures concerns inductive definitions and proofs of datatypes and programs.

More information

EDAF40. 2nd June :00-19:00. WRITE ONLY ON ONE SIDE OF THE PAPER - the exams will be scanned in and only the front/ odd pages will be read.

EDAF40. 2nd June :00-19:00. WRITE ONLY ON ONE SIDE OF THE PAPER - the exams will be scanned in and only the front/ odd pages will be read. EDAF40 2nd June 2017 14:00-19:00 WRITE ONLY ON ONE SIDE OF THE PAPER - the exams will be scanned in and only the front/ odd pages will be read. DO NOT WRITE WITH OTHER COLOUR THAN BLACK - coloured text

More information

n n Try tutorial on front page to get started! n spring13/ n Stack Overflow!

n   n Try tutorial on front page to get started! n   spring13/ n Stack Overflow! Announcements n Rainbow grades: HW1-6, Quiz1-5, Exam1 n Still grading: HW7, Quiz6, Exam2 Intro to Haskell n HW8 due today n HW9, Haskell, out tonight, due Nov. 16 th n Individual assignment n Start early!

More information

Haskell through HUGS THE BASICS

Haskell through HUGS THE BASICS Haskell through HUGS THE BASICS FP for DB Basic HUGS 1 Algorithmic Imperative Languages variables assignment if condition then action1 else action2 loop block while condition do action repeat action until

More information

Problem Set CVO 103, Spring 2018

Problem Set CVO 103, Spring 2018 Problem Set CVO 103, Spring 2018 Hakjoo Oh Due: 06/12 (in class) Problem 1 The Fibonacci numbers can be defined as follows: 0 if n = 0 fib(n) = 1 if n = 1 fib(n 1) + fib(n 2) otherwise Write in OCaml the

More information

INTRODUCTION TO FUNCTIONAL PROGRAMMING

INTRODUCTION TO FUNCTIONAL PROGRAMMING INTRODUCTION TO FUNCTIONAL PROGRAMMING Graham Hutton University of Nottingham adapted by Gordon Uszkay 1 What is Functional Programming? Opinions differ, and it is difficult to give a precise definition,

More information

PROGRAMMING IN C AND C++:

PROGRAMMING IN C AND C++: PROGRAMMING IN C AND C++: Week 1 1. Introductions 2. Using Dos commands, make a directory: C:\users\YearOfJoining\Sectionx\USERNAME\CS101 3. Getting started with Visual C++. 4. Write a program to print

More information

Honors Precalculus: Solving equations and inequalities graphically and algebraically. Page 1

Honors Precalculus: Solving equations and inequalities graphically and algebraically. Page 1 Solving equations and inequalities graphically and algebraically 1. Plot points on the Cartesian coordinate plane. P.1 2. Represent data graphically using scatter plots, bar graphs, & line graphs. P.1

More information

CSc 372 Comparative Programming Languages

CSc 372 Comparative Programming Languages CSc 372 Comparative Programming Languages 8 : Haskell Function Examples Christian Collberg collberg+372@gmail.com Department of Computer Science University of Arizona Copyright c 2005 Christian Collberg

More information

Let s Talk About Logic

Let s Talk About Logic Let s Talk About Logic Jan van Eijck CWI & ILLC, Amsterdam Masterclass Logica, 2 Maart 2017 Abstract This lecture shows how to talk about logic in computer science. To keep things simple, we will focus

More information

CSc 372. Comparative Programming Languages. 8 : Haskell Function Examples. Department of Computer Science University of Arizona

CSc 372. Comparative Programming Languages. 8 : Haskell Function Examples. Department of Computer Science University of Arizona 1/43 CSc 372 Comparative Programming Languages 8 : Haskell Function Examples Department of Computer Science University of Arizona collberg@gmail.com Copyright c 2013 Christian Collberg Functions over Lists

More information

Programming Paradigms

Programming Paradigms PP 2017/18 Unit 12 Functions and Data Types in Haskell 1/45 Programming Paradigms Unit 12 Functions and Data Types in Haskell J. Gamper Free University of Bozen-Bolzano Faculty of Computer Science IDSE

More information

Suggestive List of C++ Programs

Suggestive List of C++ Programs Suggestive List of C++ Programs 1. Write a C++ program to display Hello World! on the output screen. 2. Write a program to display Multiplication Table of a number inputted by the user. 3. Write a program

More information

Haskell Types, Classes, and Functions, Currying, and Polymorphism

Haskell Types, Classes, and Functions, Currying, and Polymorphism 1 CSCE 314: Programming Languages Dr. Flemming Andersen Haskell Types, Classes, and Functions, Currying, and Polymorphism 2 Types A type is a collection of related values. For example, Bool contains the

More information

CS 440: Programming Languages and Translators, Spring 2019 Mon

CS 440: Programming Languages and Translators, Spring 2019 Mon Haskell, Part 4 CS 440: Programming Languages and Translators, Spring 2019 Mon 2019-01-28 More Haskell Review definition by cases Chapter 6: Higher-order functions Revisit currying map, filter Unnamed

More information

Student number: Datenstrukturen & Algorithmen page 1

Student number: Datenstrukturen & Algorithmen page 1 Student number: Datenstrukturen & Algorithmen page 1 Problem 1. / 16 P Instructions: 1) In this problem, you have to provide solutions only. You can write them right on this sheet. 2) You may use the notation,

More information

CS 320: Concepts of Programming Languages

CS 320: Concepts of Programming Languages CS 320: Concepts of Programming Languages Wayne Snyder Computer Science Department Boston University Lecture 04: Basic Haskell Continued o Polymorphic Types o Type Inference with Polymorphism o Standard

More information

1.1 calculator viewing window find roots in your calculator 1.2 functions find domain and range (from a graph) may need to review interval notation

1.1 calculator viewing window find roots in your calculator 1.2 functions find domain and range (from a graph) may need to review interval notation 1.1 calculator viewing window find roots in your calculator 1.2 functions find domain and range (from a graph) may need to review interval notation functions vertical line test function notation evaluate

More information

Functional Programming TDA 452, DIT 142

Functional Programming TDA 452, DIT 142 Chalmers Göteborgs Universitet 2018-01-11 Examiner: Thomas Hallgren, D&IT, Answering questions at approx 15.00 (or by phone) Functional Programming TDA 452, DIT 142 2018-01-11 14.00 18.00 Samhällsbyggnad

More information

CSCE 314 Programming Languages

CSCE 314 Programming Languages CSCE 314 Programming Languages Haskell: Higher-order Functions Dr. Hyunyoung Lee 1 Higher-order Functions A function is called higher-order if it takes a function as an argument or returns a function as

More information

CS 457/557: Functional Languages

CS 457/557: Functional Languages CS 457/557: Functional Languages Lists and Algebraic Datatypes Mark P Jones Portland State University 1 Why Lists? Lists are a heavily used data structure in many functional programs Special syntax is

More information

Functional Programming Mid-term exam Tuesday 3/10/2017

Functional Programming Mid-term exam Tuesday 3/10/2017 Functional Programming Mid-term exam Tuesday 3/10/2017 Name: Student number: Before you begin: Do not forget to write down your name and student number above. If necessary, explain your answers in English.

More information

Shell CSCE 314 TAMU. Haskell Functions

Shell CSCE 314 TAMU. Haskell Functions 1 CSCE 314: Programming Languages Dr. Dylan Shell Haskell Functions 2 Outline Defining Functions List Comprehensions Recursion 3 Conditional Expressions As in most programming languages, functions can

More information

6.001 Notes: Section 4.1

6.001 Notes: Section 4.1 6.001 Notes: Section 4.1 Slide 4.1.1 In this lecture, we are going to take a careful look at the kinds of procedures we can build. We will first go back to look very carefully at the substitution model,

More information

Shell CSCE 314 TAMU. Higher Order Functions

Shell CSCE 314 TAMU. Higher Order Functions 1 CSCE 314: Programming Languages Dr. Dylan Shell Higher Order Functions 2 Higher-order Functions A function is called higher-order if it takes a function as an argument or returns a function as a result.

More information

Math Lesson Plan 6th Grade Curriculum Total Activities: 302

Math Lesson Plan 6th Grade Curriculum Total Activities: 302 TimeLearning Online Learning for Homeschool and Enrichment www.timelearning.com Languages Arts, Math and more Multimedia s, Interactive Exercises, Printable Worksheets and Assessments Student Paced Learning

More information

Program Calculus Calculational Programming

Program Calculus Calculational Programming Program Calculus Calculational Programming National Institute of Informatics June 21 / June 28 / July 5, 2010 Program Calculus Calculational Programming What we will learn? Discussing the mathematical

More information

Lecture 19: Functions, Types and Data Structures in Haskell

Lecture 19: Functions, Types and Data Structures in Haskell The University of North Carolina at Chapel Hill Spring 2002 Lecture 19: Functions, Types and Data Structures in Haskell Feb 25 1 Functions Functions are the most important kind of value in functional programming

More information

Exercise 1 ( = 24 points)

Exercise 1 ( = 24 points) 1 Exercise 1 (4 + 5 + 4 + 6 + 5 = 24 points) The following data structure represents polymorphic binary trees that contain values only in special Value nodes that have a single successor: data Tree a =

More information

CSE 20 DISCRETE MATH. Winter

CSE 20 DISCRETE MATH. Winter CSE 20 DISCRETE MATH Winter 2017 http://cseweb.ucsd.edu/classes/wi17/cse20-ab/ Final exam The final exam is Saturday March 18 8am-11am. Lecture A will take the exam in GH 242 Lecture B will take the exam

More information

PITSCO Math Individualized Prescriptive Lessons (IPLs)

PITSCO Math Individualized Prescriptive Lessons (IPLs) Orientation Integers 10-10 Orientation I 20-10 Speaking Math Define common math vocabulary. Explore the four basic operations and their solutions. Form equations and expressions. 20-20 Place Value Define

More information

Chapter Summary. Mathematical Induction Recursive Definitions Structural Induction Recursive Algorithms

Chapter Summary. Mathematical Induction Recursive Definitions Structural Induction Recursive Algorithms Chapter Summary Mathematical Induction Recursive Definitions Structural Induction Recursive Algorithms Section 5.1 Sec.on Summary Mathematical Induction Examples of Proof by Mathematical Induction Mistaken

More information

Reasoning About Imperative Programs. COS 441 Slides 10

Reasoning About Imperative Programs. COS 441 Slides 10 Reasoning About Imperative Programs COS 441 Slides 10 The last few weeks Agenda reasoning about functional programming It s very simple and very uniform: substitution of equal expressions for equal expressions

More information

COP4020 Programming Languages. Functional Programming Prof. Robert van Engelen

COP4020 Programming Languages. Functional Programming Prof. Robert van Engelen COP4020 Programming Languages Functional Programming Prof. Robert van Engelen Overview What is functional programming? Historical origins of functional programming Functional programming today Concepts

More information

Haskell Overview II (2A) Young Won Lim 8/9/16

Haskell Overview II (2A) Young Won Lim 8/9/16 (2A) 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

More information

Haskell 98 in short! CPSC 449 Principles of Programming Languages

Haskell 98 in short! CPSC 449 Principles of Programming Languages Haskell 98 in short! n Syntax and type inferencing similar to ML! n Strongly typed! n Allows for pattern matching in definitions! n Uses lazy evaluation" F definition of infinite lists possible! n Has

More information

The List Datatype. CSc 372. Comparative Programming Languages. 6 : Haskell Lists. Department of Computer Science University of Arizona

The List Datatype. CSc 372. Comparative Programming Languages. 6 : Haskell Lists. Department of Computer Science University of Arizona The List Datatype CSc 372 Comparative Programming Languages 6 : Haskell Lists Department of Computer Science University of Arizona collberg@gmail.com All functional programming languages have the ConsList

More information

Course year Typeclasses and their instances

Course year Typeclasses and their instances Course year 2016-2017 Typeclasses and their instances Doaitse Swierstra and Atze Dijkstra with extra s Utrecht University September 29, 2016 1. The basics 2 Overloading versus parametric polymorphism 1

More information

PROGRAMMING IN HASKELL. Chapter 2 - First Steps

PROGRAMMING IN HASKELL. Chapter 2 - First Steps PROGRAMMING IN HASKELL Chapter 2 - First Steps 0 The Hugs System Hugs is an implementation of Haskell 98, and is the most widely used Haskell system; The interactive nature of Hugs makes it well suited

More information

Recursion. Recursion is: Recursion splits a problem:

Recursion. Recursion is: Recursion splits a problem: Recursion Recursion Recursion is: A problem solving approach, that can... Generate simple solutions to... Certain kinds of problems that... Would be difficult to solve in other ways Recursion splits a

More information

DISCRETE MATHEMATICS

DISCRETE MATHEMATICS DISCRETE MATHEMATICS WITH APPLICATIONS THIRD EDITION SUSANNA S. EPP DePaul University THOIVISON * BROOKS/COLE Australia Canada Mexico Singapore Spain United Kingdom United States CONTENTS Chapter 1 The

More information

A tour of the Haskell Prelude

A tour of the Haskell Prelude A tour of the Haskell Prelude Bernie Pope 2001 1 Haskell The Haskell language was conceived during a meeting held at the 1987 Functional Programming and Computer Architecture conference (FPCA 87). At the

More information

Haskell-Tutorial. Damir Medak Gerhard Navratil. Institute for Geoinformation Technical University Vienna. February 2003

Haskell-Tutorial. Damir Medak Gerhard Navratil. Institute for Geoinformation Technical University Vienna. February 2003 Haskell-Tutorial Damir Medak Gerhard Navratil Institute for Geoinformation Technical University Vienna February 2003 There are numerous books on functional programming. These books are good, but usually

More information

CPSC 121 Some Sample Questions for the Final Exam Tuesday, April 15, 2014, 8:30AM

CPSC 121 Some Sample Questions for the Final Exam Tuesday, April 15, 2014, 8:30AM CPSC 121 Some Sample Questions for the Final Exam Tuesday, April 15, 2014, 8:30AM Name: Student ID: Signature: Section (circle one): George Steve Your signature acknowledges your understanding of and agreement

More information

Haskell An Introduction

Haskell An Introduction Haskell An Introduction What is Haskell? General purpose Purely functional No function can have side-effects IO is done using special types Lazy Strongly typed Polymorphic types Concise and elegant A First

More information

1 The smallest free number

1 The smallest free number 1 The smallest free number Introduction Consider the problem of computing the smallest natural number not in a given finite set X of natural numbers. The problem is a simplification of a common programming

More information

Prime Time (Factors and Multiples)

Prime Time (Factors and Multiples) CONFIDENCE LEVEL: Prime Time Knowledge Map for 6 th Grade Math Prime Time (Factors and Multiples). A factor is a whole numbers that is multiplied by another whole number to get a product. (Ex: x 5 = ;

More information

LECTURE 16. Functional Programming

LECTURE 16. Functional Programming LECTURE 16 Functional Programming WHAT IS FUNCTIONAL PROGRAMMING? Functional programming defines the outputs of a program as a mathematical function of the inputs. Functional programming is a declarative

More information

Catalan Numbers. Table 1: Balanced Parentheses

Catalan Numbers. Table 1: Balanced Parentheses Catalan Numbers Tom Davis tomrdavis@earthlink.net http://www.geometer.org/mathcircles November, 00 We begin with a set of problems that will be shown to be completely equivalent. The solution to each problem

More information

COP 4516: Math for Programming Contest Notes

COP 4516: Math for Programming Contest Notes COP 4516: Math for Programming Contest Notes Euclid's Algorithm Euclid's Algorithm is the efficient way to determine the greatest common divisor between two integers. Given two positive integers a and

More information

HIGHER-ORDER FUNCTIONS

HIGHER-ORDER FUNCTIONS 5 HIGHER-ORDER FUNCTIONS Haskell functions can take functions as parameters and return functions as return values. A function that does either of these things is called a higher-order function. Higher-order

More information

About the Author. Dependency Chart. Chapter 1: Logic and Sets 1. Chapter 2: Relations and Functions, Boolean Algebra, and Circuit Design

About the Author. Dependency Chart. Chapter 1: Logic and Sets 1. Chapter 2: Relations and Functions, Boolean Algebra, and Circuit Design Preface About the Author Dependency Chart xiii xix xxi Chapter 1: Logic and Sets 1 1.1: Logical Operators: Statements and Truth Values, Negations, Conjunctions, and Disjunctions, Truth Tables, Conditional

More information

CS301 - Data Structures Glossary By

CS301 - Data Structures Glossary By CS301 - Data Structures Glossary By Abstract Data Type : A set of data values and associated operations that are precisely specified independent of any particular implementation. Also known as ADT Algorithm

More information

Lecture 5: Lazy Evaluation and Infinite Data Structures

Lecture 5: Lazy Evaluation and Infinite Data Structures Lecture 5: Lazy Evaluation and Infinite Data Structures Søren Haagerup Department of Mathematics and Computer Science University of Southern Denmark, Odense October 3, 2017 How does Haskell evaluate a

More information

CSE 20 DISCRETE MATH. Fall

CSE 20 DISCRETE MATH. Fall CSE 20 DISCRETE MATH Fall 2017 http://cseweb.ucsd.edu/classes/fa17/cse20-ab/ Final exam The final exam is Saturday December 16 11:30am-2:30pm. Lecture A will take the exam in Lecture B will take the exam

More information

We assume uniform hashing (UH):

We assume uniform hashing (UH): We assume uniform hashing (UH): the probe sequence of each key is equally likely to be any of the! permutations of 0,1,, 1 UH generalizes the notion of SUH that produces not just a single number, but a

More information

Smarter Balanced Vocabulary (from the SBAC test/item specifications)

Smarter Balanced Vocabulary (from the SBAC test/item specifications) Example: Smarter Balanced Vocabulary (from the SBAC test/item specifications) Notes: Most terms area used in multiple grade levels. You should look at your grade level and all of the previous grade levels.

More information

SHAPE, SPACE & MEASURE

SHAPE, SPACE & MEASURE STAGE 1 Know the place value headings up to millions Recall primes to 19 Know the first 12 square numbers Know the Roman numerals I, V, X, L, C, D, M Know the % symbol Know percentage and decimal equivalents

More information

Draw a diagram of an empty circular queue and describe it to the reader.

Draw a diagram of an empty circular queue and describe it to the reader. 1020_1030_testquestions.text Wed Sep 10 10:40:46 2014 1 1983/84 COSC1020/30 Tests >>> The following was given to students. >>> Students can have a good idea of test questions by examining and trying the

More information

www.thestudycampus.com Recursion Recursion is a process for solving problems by subdividing a larger problem into smaller cases of the problem itself and then solving the smaller, more trivial parts. Recursion

More information

CS1800 Discrete Structures Fall 2016 Profs. Aslam, Gold, Ossowski, Pavlu, & Sprague December 16, CS1800 Discrete Structures Final

CS1800 Discrete Structures Fall 2016 Profs. Aslam, Gold, Ossowski, Pavlu, & Sprague December 16, CS1800 Discrete Structures Final CS1800 Discrete Structures Fall 2016 Profs. Aslam, Gold, Ossowski, Pavlu, & Sprague December 16, 2016 Instructions: CS1800 Discrete Structures Final 1. The exam is closed book and closed notes. You may

More information

8 th Grade Mathematics Unpacked Content For the new Common Core standards that will be effective in all North Carolina schools in the

8 th Grade Mathematics Unpacked Content For the new Common Core standards that will be effective in all North Carolina schools in the 8 th Grade Mathematics Unpacked Content For the new Common Core standards that will be effective in all North Carolina schools in the 2012-13. This document is designed to help North Carolina educators

More information

Programming in Haskell Aug-Nov 2015

Programming in Haskell Aug-Nov 2015 Programming in Haskell Aug-Nov 2015 LECTURE 14 OCTOBER 1, 2015 S P SURESH CHENNAI MATHEMATICAL INSTITUTE Enumerated data types The data keyword is used to define new types data Bool = False True data Day

More information

Texas High School Geometry

Texas High School Geometry Texas High School Geometry This course covers the topics shown below. Students navigate learning paths based on their level of readiness. Institutional users may customize the scope and sequence to meet

More information

Title: Recursion and Higher Order Functions

Title: Recursion and Higher Order Functions Programing Paradigms and Languages Title: Recursion and Higher Order Functions Students: Ysee Monir, Besart Vishesella Proffesor: Dr. Robert Kowalczyk In this presentation, we'll take a closer look at

More information

KS3 Curriculum Plan Maths - Core Year 7

KS3 Curriculum Plan Maths - Core Year 7 KS3 Curriculum Plan Maths - Core Year 7 Autumn Term 1 Unit 1 - Number skills Unit 2 - Fractions Know and use the priority of operations and laws of arithmetic, Recall multiplication facts up to 10 10,

More information

Introduction to Functional Programming in Haskell 1 / 56

Introduction to Functional Programming in Haskell 1 / 56 Introduction to Functional Programming in Haskell 1 / 56 Outline Why learn functional programming? The essence of functional programming What is a function? Equational reasoning First-order vs. higher-order

More information

Introduction to Programming: Lecture 6

Introduction to Programming: Lecture 6 Introduction to Programming: Lecture 6 K Narayan Kumar Chennai Mathematical Institute http://www.cmi.ac.in/~kumar 28 August 2012 Example: initial segments Write a Haskell function initsegs which returns

More information

The Common Curriculum Framework. for K 9 MATHEMATICS. Western and Northern Canadian Protocol. May 2006

The Common Curriculum Framework. for K 9 MATHEMATICS. Western and Northern Canadian Protocol. May 2006 The Common Curriculum Framework for K 9 MATHEMATICS Western and Northern Canadian Protocol May 2006 Grade 5 Strand: Number 1. Represent and describe whole numbers to 1 000 000. [C, CN, V, T] 2. Use estimation

More information

CS 209 Functional Programming

CS 209 Functional Programming CS 209 Functional Programming Lecture 03 - Intro to Monads Dr. Greg Lavender Department of Computer Science Stanford University "The most important thing in a programming language is the name. A language

More information

Things to Know for the Algebra I Regents

Things to Know for the Algebra I Regents Types of Numbers: Real Number: any number you can think of (integers, rational, irrational) Imaginary Number: square root of a negative number Integers: whole numbers (positive, negative, zero) Things

More information

Matija Gubec International School Zagreb MYP 0. Mathematics

Matija Gubec International School Zagreb MYP 0. Mathematics Matija Gubec International School Zagreb MYP 0 Mathematics 1 MYP0: Mathematics Unit 1: Natural numbers Through the activities students will do their own research on history of Natural numbers. Students

More information

Topic 6: Partial Application, Function Composition and Type Classes

Topic 6: Partial Application, Function Composition and Type Classes Topic 6: Partial Application, Function Composition and Type Classes Recommended Exercises and Readings From Haskell: The craft of functional programming (3 rd Ed.) Exercises: 11.11, 11.12 12.30, 12.31,

More information

Topic 6: Partial Application, Function Composition and Type Classes

Topic 6: Partial Application, Function Composition and Type Classes Topic 6: Partial Application, Function Composition and Type Classes 1 Recommended Exercises and Readings From Haskell: The craft of functional programming (3 rd Ed.) Exercises: 11.11, 11.12 12.30, 12.31,

More information

Anadarko Public Schools MATH Power Standards

Anadarko Public Schools MATH Power Standards Anadarko Public Schools MATH Power Standards Kindergarten 1. Say the number name sequence forward and backward beginning from a given number within the known sequence (counting on, spiral) 2. Write numbers

More information

Abacus 5 and 6: Autumn term 1st half UNIT TOPIC ABACUS 5 UNITS ABACUS 6 UNITS 1 Place-value, ordering and rounding

Abacus 5 and 6: Autumn term 1st half UNIT TOPIC ABACUS 5 UNITS ABACUS 6 UNITS 1 Place-value, ordering and rounding Abacus 5 and 6: Autumn term 1st half 1 Place-value, ordering and rounding N2 Place-value To round any number up to 10 000 to the nearest ten, hundred or thousand N1 Place-value To rehearse rounding a number

More information

Programming Languages Fall 2013

Programming Languages Fall 2013 Programming Languages Fall 2013 Lecture 2: types Prof. Liang Huang huang@qc.cs.cuny.edu Recap of Lecture 1 functional programming vs. imperative programming basic Haskell syntax function definition lazy

More information

Programming Language Concepts: Lecture 14

Programming Language Concepts: Lecture 14 Programming Language Concepts: Lecture 14 Madhavan Mukund Chennai Mathematical Institute madhavan@cmi.ac.in http://www.cmi.ac.in/~madhavan/courses/pl2009 PLC 2009, Lecture 14, 11 March 2009 Function programming

More information

Interactive Math Glossary Terms and Definitions

Interactive Math Glossary Terms and Definitions Terms and Definitions Absolute Value the magnitude of a number, or the distance from 0 on a real number line Addend any number or quantity being added addend + addend = sum Additive Property of Area the

More information

CSC148, Lab #4. General rules. Overview. Tracing recursion. Greatest Common Denominator GCD

CSC148, Lab #4. General rules. Overview. Tracing recursion. Greatest Common Denominator GCD CSC148, Lab #4 This document contains the instructions for lab number 4 in CSC148H. To earn your lab mark, you must actively participate in the lab. We mark you in order to ensure a serious attempt at

More information

II (Sorting and) Order Statistics

II (Sorting and) Order Statistics II (Sorting and) Order Statistics Heapsort Quicksort Sorting in Linear Time Medians and Order Statistics 8 Sorting in Linear Time The sorting algorithms introduced thus far are comparison sorts Any comparison

More information

DEPARTMENT OF MATHS, MJ COLLEGE

DEPARTMENT OF MATHS, MJ COLLEGE T. Y. B.Sc. Mathematics MTH- 356 (A) : Programming in C Unit 1 : Basic Concepts Syllabus : Introduction, Character set, C token, Keywords, Constants, Variables, Data types, Symbolic constants, Over flow,

More information

Recursion and Induction: Haskell; Primitive Data Types; Writing Function Definitions

Recursion and Induction: Haskell; Primitive Data Types; Writing Function Definitions Recursion and Induction: Haskell; Primitive Data Types; Writing Function Definitions Greg Plaxton Theory in Programming Practice, Spring 2005 Department of Computer Science University of Texas at Austin

More information