I am having trouble with my Scala program. This assignment focuses on some of th
ID: 3813694 • Letter: I
Question
I am having trouble with my Scala program.
This assignment focuses on some of the more advanced features of Scala, including: • stackable traits and abstract override methods; • iterators and the difficulties involved in working with them; • streams and the danger of memory leaks; • implicit conversions.
Heres a quick description followed by the implementation I am having trouble with!
1 Description of the Framework
1.1 Document sources
The package to develop implements a notion of document source. A document source is similar to an iterator but produces its contents either as characters or as words, whichever is most convenient to the underlying application. As with iterators, words and characters are produced “on the fly” and are not stored. Correct implementations of document sources should be able to handle large documents without loading them entirely in memory. A document source offers two methods: • chars: produces the contents of the document as an iterator of characters; • words: produces the contents of the document as an iterator of words. Application code is expected to use one or the other of these methods, but not both, as they draw their contents from the same source and using one after the other has already produced elements would be unreliable. A typical use of a document source has the form: for (char <- docSource.chars) {...} or for (word <- docSource.words) {...} In addition to these two methods, a document source can be enriched by adding the so-called “monadic” methods: foreach, withFilter, map and flatMap. 1 Those work in terms of characters and can be used to process or transform the document. Like standard iterators, document sources usually become invalid once one of their methods has been called. Unless stated otherwise, only one of the six methods chars, words, foreach, withFilter, map or flatMap can be called on a document source, and it can only be called once. The monadic methods are parts of a “rich” document source type. Regular document sources can be converted into rich sources via implicit conversions. This enables an application to write: for (c <- docSource) ... instead of the equivalent: for (c <- docSource.chars) ... 1For the sake of simplicity, they have slightly reduced signatures compared to their counterparts in trait FilterMonadic. 1 / 5
1.2 Document transformations
Document sources can be transformed at the level of characters or at the level of words. These transformations are handled through stackable traits. Traits that extend the Transformer trait can be mixed in document sources to introduce processing on both words and characters (filtering, transformation, etc.). One difficulty that arises is that documents can be transformed in terms of words and/or characters and then consumed as words or as characters. For instance, a document can have its characters converted to uppercase and then fed as words to a document reader that will arrange words in lines. Or a document can have its accented letters converted, some of its words censored, and then be sent through a socket as packets of characters. Without knowing how exactly a document is to be transformed, an implementation runs the risk of introducing cycles: derive the characters from the words (to send character packets), which are derived from the characters (to convert accented letters), which are derived from the words (to remove censored words), etc. This assignment relies on a base trait CharSource, in which a document’s characters are defined in terms of its words, which are defined in terms of its source (of characters). The characters of the document always derive from the words and the words always derive from the source. Character-level transformations are applied to the source—and are therefore reflected in both the words and the characters of the document— while word-level transformations are applied directly to the words and are reflected in the characters (but not in the source).
This is the issue I am having:
Class IteratorDocumentSource
"This class provides us with a default implementation of the type RichDocumentSource. It can be used to mix
in traits in various combinations and observe the results. Note that this class implements the full (“rich”)
document source interface, including the monadic operators."
I do not know how to implement the IteratorDocumentSource class. I attempted 'for-each'. I understand monads but I do not know how to do this with an iterator of words at the char level and do not know how to return type IteratorDocumentSource. Whenever I try to write map like this:
def map(f: (Char) => Char): IteratorDocumentSource = {
val it = iterator
while (it.hasNext) {
val x = for (i <- it) yield f(i)//f(i)
it.next()
}
It wants to return an Iterator[Char] not IteratorDocumentSource. Here is the IteratorDocumentSource class:
package document
class IteratorDocumentSource(iterator: Iterator[Char]) extends CharSource with RichDocumentSource {
protected def source: Iterator[Char] = ???
def foreach[A](f: (Char) => A): Unit = {
val it = iterator
while (it.hasNext) {
f(it)
it.next()
}
}
def map(f: (Char) => Char): IteratorDocumentSource = ???
def flatMap(f: (Char) => TraversableOnce[Char]): IteratorDocumentSource = ???
def withFilter(f: (Char) => Boolean): IteratorDocumentSource = ???
}
**This is RichDocumentSource:**
package document
/** A rich document source.
* It extends a regular document source with the so-called "monadic" functions:
* `foreach`, `withFilter`, `map` and `flatMap`. Those operate at the ''character'' level, not on
* words.
*
*/
trait RichDocumentSource extends DocumentSource {
/** Applies the given function to all the characters in the document. */
def foreach[A](f: (Char) => A): Unit
/** A new document obtained by applying the given transformation to all the characters of this
* document.
*/
def map(f: (Char) => Char): RichDocumentSource
/** A new document obtained by applying the given transformation to all the characters of this
* document.
*/
def flatMap(f: (Char) => TraversableOnce[Char]): RichDocumentSource
/** A new document obtained by applying the given filter to all the characters of this document.
*/
def withFilter(f: (Char) => Boolean): RichDocumentSource
}
A document source offers two methods:
• chars: produces the contents of the document as an iterator of characters;
• words: produces the contents of the document as an iterator of words
This is my charSource implementation:
package document
import scala.collection.mutable.ListBuffer
trait CharSource extends DocumentSource {
protected def source: Iterator[Char]
def words: Iterator[String] = {
val buffer = source.buffered
val sb = new StringBuilder
var words : ListBuffer[String] = ListBuffer[String] ()
while( buffer.hasNext ) {
if( !buffer.head.isWhitespace )
{
sb.append(buffer.head)
buffer.next()
}
else {
sb.append(buffer.head)
words += sb.toString()
sb.clear()
buffer.next()
}
}
if( !sb.isEmpty ){
words += sb.toString()
}
words.iterator
}
final def chars: Iterator[Char] = words.toString().toIterator
}
Explanation / Answer
#include <iostream>
#include <list>
using namespace std;
// a category that represents Associate in Nursing adrift graph
class Graph
closeness lists
public:
// builder and destructor
Graph(int V)
~Graph()
// perform to feature a foothold to graph
void addEdge(int v, int w);
// Prints greedy coloring of the vertices
void greedyColoring();
};
void Graph::addEdge(int v, int w)
{
adj[v].push_back(w);
adj[w].push_back(v); // Note: the graph is adrift
}
// Assigns colours (starting from 0) to all or any vertices and prints
// the assignment of colours
void Graph::greedyColoring()
1st|the primary} color to first vertex
result[0] = 0;
// Initialize remaining guided missile vertices as unassigned
for (int u = 1; u < V; u++)
result[u] = -1; // no color is assigned to u
// a brief array to store the on the market colours. True
// worth of available[cr] would mean that the colour metal is
// assigned to at least one of its adjacent vertices
bool available[V];
for (int metal = 0; metal < V; cr++)
available[cr] = false;
// Assign colours to remaining guided missile vertices
for (int u = 1; u < V; u++)
method all adjacent vertices and flag their colours
// as unobtainable
list<int>::iterator i;
for (i = adj[u].begin(); i != adj[u].end(); ++i)
if (result[*i] != -1)
available[result[*i]] = true;
// realize the primary on the market color
int cr;
for (cr = 0; metal < V; cr++)
if (available[cr] == false)
break;
result[u] = cr; // Assign the found color
// Reset the values back to false for successive iteration
for (i = adj[u].begin(); i != adj[u].end(); ++i)
if (result[*i] != -1)
available[result[*i]] = false;
}
// print the result
for (int u = 0; u < V; u++)
cout << "Vertex " << u << " ---> Color "
<< result[u] << endl;
}
// Driver program to check higher than perform
int main()
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.