This is an old revision of the document!
Introduction to Functional Programming (in Java!)
1. A single function to implement all of them
1.1. Write a method that takes a list of integers and returns a new list with all elements multiplied by two.
1.2. Write a method that takes a list of doubles and returns a new list with all elements multiplied by two.
1.3. Write a method that takes a list of integers and returns a new list with all the elements’ successors (i.e. the elements incremented by 1).
1.4. Write a method that takes a list of integers and returns a new list of booleans indicating if an element is prime.
1.5. (Discussion) What is common among all previous implementations? Could a single list function (a more general function) be used to achieve all results? Starting from the signatures of previous functions, write the signature for this general function which we will call map.
1.6. (Discussion) How can we pass functions as parameter (to another function) in Java? Consider unary functions of the form: $ f : A \rightarrow B$ (where $ A$ and $ B$ are generic).
1.7. (!) Write an implementation for map
.
2. Throwing out elements ...
2.1. Write a method that takes a list of integers and returns a new list containing only even elements.
2.2. Write a method that takes a list of integers and returns a new list containing the elements larger than 100.
2.3. Write a method that takes a list of integers and returns a new list containing even elements larger than 100.
d. Write a method that takes a list of integers and returns a new list of the elements which are prime
2.4. (!) Write the signature of a generic filter
function over lists.
2.5. (!!) Implement filter
.
3. Reducing lists
3.1. Write a method that takes a list of integers and returns the sum of all the elements.
3.2. Write a method that takes a list of integers and returns the product of all the elements.
3.3. Write a method that takes a list of integers and returns a string representation of all elements separated by commas, e.g. “1,2,3,4”
3.4. Write a method that takes a list of integers and another list (of integers) and returns the concatenation of the second to the first.
3.5. (Discussion) What is (could be!) common among all implementations? How should a fold
function signature (which generalises over all previous ones) look like?
3.6. (!) Implement fold
with all its prerequisites.