Introductory Programming In Java
| Lab 1 |
Lab 2 |
Lab 3 |
Lab 4 |
Lab 5 |
Lab 6 |
Lab 7 |
Lab 7
Functional Programming in Java
Objectives
To introduce the functional programming style, and expose Java's limitation in it.
Preparations
Exercise One: High-order functions in Java
A high-order function takes other functions as arguments or return them as result.
A typical example is map(func, collection) —
it will take a collection of values ci, one-by-one, and apply the
function func to them, func(ci) and insert
the result fi into another collection which it will return.
Java cannot do such computations directly because it doesn't have high-order functions. It has to simulate. Since passing a function as an argument means passing a code for execution, we would use the way we know --- the inner classes.
Start with defining an interface called Function with only one method
inside it: operate(). To make it as versatile as possible, make it
a varag method of the most generic type: Object operate(Object... arg).
Then write a method List map(Function, collection)
by using everything you know about anonymous inner classes to perform
the following manipulation with a collection object:
map a list of objects to a collection of their string representations
map a list of objects to a collection of their hash codes
filter (ie, include only those elements in the returning collection which evaluate to
trueby the Function object assuming it'soperate()method returns a boolean value) a collection of objectsreduce a list to a single value of their element type when the
Function.operate(o1,o2)takes two arguments and returns the value of the element type. Can you definereduce()recursively?
Write a client code which will make use of the above high-order function in more then one cases where lists of elements with different types are involved.
Exercise Two: More Functional Programming
Once successful, consider the following problems:
How the interface Function and its implementation in a high-order function argument can be made generic (ie, using parameterised types)?
How
mapand other high-order functions can be made more versatile so the use of a particular collection type will automatically select a correct function argument (such that operations which are involved inoperate(...)are well defined for the collection element type).
| Lab 1 |
Lab 2 |
Lab 3 |
Lab 4 |
Lab 5 |
Lab 6 |
Lab 7 |
