object TernaryBit {
    val P = TernaryBit(+1)
    val M = TernaryBit(-1)
    val Z = TernaryBit( 0)

  implicit def asChar(t: TernaryBit): Char = t.charValue 
  implicit def valueOf(c: Char): TernaryBit = {
    c match {
      case '0' => 0
      case '+' => 1
      case '-' => -1
      case nc => throw new IllegalArgumentException("Illegal ternary symbol " + nc)
    }
  }
  implicit def asInt(t: TernaryBit): Int = t.intValue
  implicit def valueOf(i: Int): TernaryBit = TernaryBit(i)
}

case class TernaryBit(val intValue: Int) {

    def inverse: TernaryBit = TernaryBit(-intValue)

    def charValue = intValue match {
      case  0 => '0'
      case  1 => '+'
      case -1 => '-'
    }
}

class Ternary(val bits: List[TernaryBit]) {

  def + (b: Ternary) = {
    val sumBits: List[Int] = bits.map(_.intValue).zipAll(b.bits.map(_.intValue), 0, 0).map(p => p._1 + p._2)