Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package tables
- import tables.Table.Row
- class Table(val name: String, val attrs: List[String], val lines: List[List[Any]]) {
- // Secondary constructor for anonym tables
- def this(attrs: List[String], lines: List[List[Any]]) {
- this("", attrs, lines)
- }
- def display() = {
- println(name)
- println(attrs)
- for (l <- lines) {
- println(l)
- }
- }
- def project(newAttrs: List[String]): Table = {
- var newLines: List[Row] = Nil
- for (l <- lines) {
- var newLine: Row = Nil
- for (a <- newAttrs) {
- newLine = newLine ::: List(Table.get(a, attrs, l))
- }
- newLines = newLines ::: List(newLine)
- }
- new Table(newAttrs, newLines)
- }
- // High order version
- def projectHo(newAttrs: List[String]): Table =
- new Table(newAttrs, lines.map(l => newAttrs.map(a => Table.get(a, newAttrs, l))))
- def alias(als: Map[String, String]) : Table = {
- var newAttrs: List[String] = Nil
- for (a <- newAttrs) {
- newAttrs = newAttrs ::: List(if (als.contains(a)) als(a) else a)
- }
- new Table(newAttrs, lines)
- }
- // High order version
- def aliasHo(als: Map[String, String]) : Table =
- new Table(attrs.map(a => if (als.contains(a)) als(a) else a), lines)
- def select(predicate: Row => Boolean): Table = {
- var newLines: List[Row] = Nil
- for(r <- lines ){
- if(predicate.apply(r)) r :: newLines
- }
- new Table(attrs, newLines)
- }
- // High order version
- def selectHo(predicate: Row => Boolean): Table = new Table(attrs, lines.filter(predicate))
- def product(that: Table): Table = {
- val newAttrs : List[String] = this.attrs
- for(a <- that.attrs){
- a :: newAttrs
- }
- val newLines: List[Row] = Nil
- for(r <- that.lines){
- for(rr <- this.lines){
- (r++rr)::newLines
- }
- }
- new Table(newAttrs, newLines)
- }
- // High order version
- def join(that: Table, attributeThis: String, attributeThat: String, predicate: (Any, Any) => Boolean): Table = {
- val p = product(that)
- new Table(p.attrs, p.lines.filter(l => predicate(l(p.attrs.indexOf(attributeThis)),
- l(p.attrs.indexOf(attributeThat)))))
- }
- }
- object Table {
- type Row = List[Any]
- def get(attr: String, attrs: List[String] ,row: Row): Any = row(attrs.indexOf(attr))
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement