AsyncFP Sequences - laforge49/Asynchronous-Functional-Programming GitHub Wiki
In AsyncFP, Sequence is a subclass of Actor. Sequence objects support a Functional Programming approach, e.g. filter, fold, map, etc. Sequences are a succession of key/value pairs, which means you can also do things like merge and intersection. There are two basic types of sequences:
- Computed sequences and
- Sequences which operate over a data structure.
The simplest and likely the most useful sequence is Range, which provides a sequence over a range of integers. Similarly, one of the simplest and most generic message that can be sent to a sequence is Loop.
Lets start by looking at the Loop message:
case class Loop[K, V](f: (K, V) => Unit)
A loop message takes a single argument--a function which is called for each key/value pair in the sequence.
Looping without a sequence can be difficult, as messages are passed to an actor via its apply method, passing a message and a callback function as arguments. The problem arises because the callback function may be called either before or after the apply method returns, making for a bit of messy code. But looping over a sequence is quite straight forward:
val range = new Range(4, 8)
Future(range, Loop {
(key: Int, value: Int) => {
println(key + " -> " + value)
}
})
Output:
4 -> 4
5 -> 5
6 -> 6
7 -> 7
In the above test code, we use a Future to execute the Loop. Future takes two arguments, an actor and a message, and returns the result.