Mercurial > hg > Members > nobuyasu > scala
comparison chapter10/Element.scala @ 0:b316eec6fa7a draft default tip
add sample files
author | Nobuyasu Oshiro <dimolto@cr.ie.u-ryukyu.ac.jp> |
---|---|
date | Tue, 08 Jan 2013 16:41:46 +0900 |
parents | |
children |
comparison
equal
deleted
inserted
replaced
-1:000000000000 | 0:b316eec6fa7a |
---|---|
1 object Element { | |
2 private class ArrayElement( | |
3 val contents: Array[String] | |
4 ) extends Element | |
5 private class LineElement(s: String) extends Element { | |
6 val contents = Array(s) | |
7 override def width = s.length | |
8 override def height = 1 | |
9 } | |
10 private class UniformElement( | |
11 ch: Char, | |
12 override val width: Int, | |
13 override val height: Int | |
14 ) extends Element { | |
15 private val line = ch.toString * width | |
16 def contents = Array.make(height, line) | |
17 } | |
18 def elem(contents: Array[String]): Element = | |
19 new ArrayElement(contents) | |
20 def elem(chr: Char, width: Int, height: Int): Element = | |
21 new UniformElement(chr, width, height) | |
22 def elem(line: String): Element = | |
23 new LineElement(line) | |
24 } | |
25 | |
26 import Element.elem | |
27 abstract class Element { | |
28 def contents: Array[String] | |
29 def width: Int = | |
30 if (height == 0) 0 else contents(0).length | |
31 def height: Int = contents.length | |
32 def above(that: Element): Element = { | |
33 val this1 = this widen that.width | |
34 val that1 = that widen this.width | |
35 elem(this1.contents ++ that1.contents) | |
36 } | |
37 def beside(that: Element): Element = { | |
38 val this1 = this heighten that.height | |
39 val that1 = that heighten this.height | |
40 elem ( | |
41 for ((line1, line2) <- this1.contents zip that1.contents) | |
42 yield line1 + line2) | |
43 } | |
44 def widen(w: Int): Element = | |
45 if (w <= width) this | |
46 else { | |
47 val left = elem(' ', (w - width) / 2, height) | |
48 val right = elem(' ', w- width - left.width, height) | |
49 left beside this beside right | |
50 } | |
51 def heighten(h: Int): Element = | |
52 if (h <= height) this | |
53 else { | |
54 val top = elem(' ', width, (h - height) / 2) | |
55 var bot = elem(' ', width, h - height - top.height) | |
56 top above this above bot | |
57 } | |
58 override def toString = contents mkString "\n" | |
59 } | |
60 | |
61 |