Skip to content

Instantly share code, notes, and snippets.

@ib84
Created February 29, 2012 11:36
Show Gist options
  • Save ib84/1940229 to your computer and use it in GitHub Desktop.
Save ib84/1940229 to your computer and use it in GitHub Desktop.
recursive text type
package test
import scala.annotation.tailrec
import scala.collection.JavaConversions._
import scala.reflect.BeanProperty
sealed abstract class Text{
override def toString():String
//ToDo -- checkout Type bounds
//def append[A >: Text](text2:A):A
final def count(t:Text):Int = t match {
case Word(e) => 1
case Sentence(x) => x.size
}
//@tailrec (impossible to make this tailrec?)
final def recursiveCount(t:Text, result:Int = 0):Int = t match {
case Word (e) => result + 1
case Sentence(x) if x.size == 1 => recursiveCount(x.head, result)
case Sentence(x) if x.size > 1 => recursiveCount(x.head, result) + recursiveCount(Sentence(x.tail), result)
}
final def flatten(text: Text = this, sb: StringBuilder): Unit = text match{
case Word(e) => sb.append(e)
case Sentence(s) => s.foreach(t => flatten(t, sb))
}
}
case class Word(@scala.reflect.BeanProperty e : String) extends Text {
override def toString():String = {e}
//override def append(text2:Text):Text = text2 match { case Word => Sentence(List(this,text2)) /*.asInstanceOf[Text])) */ case Sentence => Sentence(List(this) ++ text2.asInstanceOf[Sentence].s)
def append(word2:Word):Sentence = Sentence(List(this,word2))
}
case class Sentence(@scala.reflect.BeanProperty s : List[Text]) extends Text {
override def toString():String = ((this.s.head.toString() /: this.s.tail)(_ + " " + _.toString()))
def append(text2:Sentence):Sentence= append(this, text2)
def append(text1: Sentence, text2:Sentence):Sentence= Sentence(text1.s ++ text2.s)
}
object Text{
def apply(s: String, s1: String):Text = {
val text1 = Text(s)
val text2= Text(s1)
Sentence(List(text1,text2))
}
//Todo -- replace "POINT" etc with unused ASCI control chars
def apply(s: String):Text ={
val textList = s.replaceAllLiterally (", ", " KOMMA ").replaceAllLiterally (". ", " POINT ").replaceAllLiterally ("? ", " QUESTIONMARK ").replaceAllLiterally ("! ", " EXCLAMATION ").split(" ").toList
println ("text.size is: " + textList.size)
if (textList.size == 0) Word("") else if (textList.size == 1) Word(textList.head) else Sentence((Word(textList.head) :: textList.tail.map(s => Word(s))))
}
def apply(striLi:List[String]):Text= if (striLi.size == 1) Text(striLi.head) else Sentence(striLi.map( s => Text(s)).toList)
}
@ib84
Copy link
Author

ib84 commented Mar 2, 2012

still work in progress but now has append methods, proper toString, (shallow) count and deep=recursive count.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment