1 /* Title: Pure/library.scala
9 import java.lang.System
10 import java.awt.Component
11 import javax.swing.JOptionPane
18 def separate[A](s: A, list: List[A]): List[A] =
20 case x :: xs if !xs.isEmpty => x :: s :: separate(s, xs)
25 /* reverse CharSequence */
27 class Reverse(text: CharSequence, start: Int, end: Int) extends CharSequence
29 require(0 <= start && start <= end && end <= text.length)
31 def this(text: CharSequence) = this(text, 0, text.length)
33 def length: Int = end - start
34 def charAt(i: Int): Char = text.charAt(end - i - 1)
36 def subSequence(i: Int, j: Int): CharSequence =
37 if (0 <= i && i <= j && j <= length) new Reverse(text, end - j, end - i)
38 else throw new IndexOutOfBoundsException
40 override def toString: String =
42 val buf = new StringBuilder(length)
43 for (i <- 0 until length)
50 /* iterate over chunks (cf. space_explode/split_lines in ML) */
52 def chunks(source: CharSequence, sep: Char = '\n') = new Iterator[CharSequence]
54 private val end = source.length
55 private def next_chunk(i: Int): Option[(CharSequence, Int)] =
58 var j = i; do j += 1 while (j < end && source.charAt(j) != sep)
59 Some((source.subSequence(i + 1, j), j))
63 private var state: Option[(CharSequence, Int)] = if (end == 0) None else next_chunk(-1)
65 def hasNext(): Boolean = state.isDefined
66 def next(): CharSequence =
68 case Some((s, i)) => { state = next_chunk(i); s }
69 case None => throw new NoSuchElementException("next on empty iterator")
76 private def simple_dialog(kind: Int, default_title: String)
77 (parent: Component, title: String, message: Any*)
79 JOptionPane.showMessageDialog(parent,
80 message.toArray.asInstanceOf[Array[AnyRef]],
81 if (title == null) default_title else title, kind)
84 def dialog = simple_dialog(JOptionPane.PLAIN_MESSAGE, null) _
85 def warning_dialog = simple_dialog(JOptionPane.WARNING_MESSAGE, "Warning") _
86 def error_dialog = simple_dialog(JOptionPane.ERROR_MESSAGE, "Error") _
91 def timeit[A](message: String)(e: => A) =
93 val start = System.currentTimeMillis()
94 val result = Exn.capture(e)
95 val stop = System.currentTimeMillis()
97 (if (message.isEmpty) "" else message + ": ") + (stop - start) + "ms elapsed time")