AnalogueRectangle.scala

package net.snowtiger.analogue

/**
 * An AnalogueRectangle provides a way of creating a pair of natural numbers
 * (width, height) using a pictographic representation.
 * See http://snowtiger.net/scala/analogue for a complete article on the subject.
 *
 * Note that the base class companion object must be imported
 * (using import AnalogueLiteral._) in order to use the required constants and
 * implicit type conversions.
 *
 * @author Mark B Davies
 */
class AnalogueRectangle(x: Int, y: Int) extends AnalogueLiteral
{
	val width = floor(x)
	val height = floor(y)

	def area() = width*height

	def top() = new AnalogueLine(width)
	def side() = new AnalogueLine(height)

	override def equals(obj: Any) =
	{
		obj match
		{
			case other:AnalogueRectangle =>
				width==other.width && height==other.height
			case _ => false
		}
	}

	// Square construction
	def incHeight() = new AnalogueRectangle(width, height+1)

	def |(other: AnalogueLine) = incHeight()
	def |~(other: AnalogueLine) = incHeight()
	def |~~(other: AnalogueLine) = incHeight()
	def |~~~(other: AnalogueLine) = incHeight()
	def |~~~~(other: AnalogueLine) = incHeight()
	def |~~~~~(other: AnalogueLine) = incHeight()
	def |~~~~~~(other: AnalogueLine) = incHeight()
	def |~~~~~~~(other: AnalogueLine) = incHeight()
	def |~~~~~~~~(other: AnalogueLine) = incHeight()
	def |~~~~~~~~~(other: AnalogueLine) = incHeight()

	// Helpers for constructing cubes
	def |+(other: AnalogueLine) = incHeight()
	def |!(other: AnalogueLine) = incHeight()

	// Arithmetic operations on rectangles
	def +(other: AnalogueRectangle) =
			new AnalogueRectangle(width+other.width, height+other.height)
	def +(other: Int) = new AnalogueRectangle(width+other, height+other)
	def *(other: Int) = new AnalogueRectangle(width*other, height*other)


	def sizeString =
	{
		"("+width+"x"+height+")=" + area
	}

	def pictureString =
	{
		val top = new AnalogueLine(width).pictureString()
		val mid = "|"+" "*(width-1)+"I\n"
		if (width==0)
			"O"
		else
			top + "\n" + mid*(height-1) + "|" + top.substring(1)
	}
}