9

I implemented a ternary operator like Java's <condition> ? <if true> : <if false>, substituting / for :, since : is not a valid identifier:

case class Ternary[T](val o: Option[T]) {
  def / (f: => T) = o getOrElse f
}

implicit def boolToTernary(cond: Boolean) = new {
  def ? [T](f: => T) = if(cond) Ternary(Some(f)) 
                        else    Ternary[T](None)
}

It works fine in general, e.g.

scala> (1 > 2) ? "hi" / "abc"
res9: java.lang.String = abc

but falls down in the following case:

scala> (1 > 2) ? 5 / 6.0
<console>:33: error: type mismatch;
 found   : Double(6.0)
 required: Int
       (1 > 2) ? 5 / 6.0
                     ^

Is there any tweaking I can do to the types in order to get this to work like the built-in if (1 > 2) 5 else 6.0 does? I googled for similar solutions and the implementations I found all exhibited the same behaviour.

Luigi Plinge
  • 50,650
  • 20
  • 113
  • 180

3 Answers3

12

One thing you can do is change your definition of / to this:

def /[U >: T](f: => U) = o getOrElse f

It doesn't work like a regular if (where the inferred type would be Double) — you get AnyVal, but that's already an improvement with a very small modification to your code.

Update: I think I've found a (slightly more complicated) way to make it behave more like a normal if (e.g., in this case, inferring a Double). Try this code:

implicit def boolToTernary(cond: Boolean) = new {
  def ?[T](f: => T) = if (cond) Ternary(Some(f))
  else Ternary[T](None)
}

case class Ternary[T](val o: Option[T]) {
  def /[U, That](f: => U)(implicit conv: BiConverter[T, U, That]): That = o map conv.toThat1 getOrElse (conv toThat2 f)
}

class BiConverter[T, U, That](val toThat1: T => That, val toThat2: U => That)

trait LowPriorityBiConverterImplicits {
  implicit def subtype[A, T <: A, U <: A]: BiConverter[T, U, A] = new BiConverter[T, U, A](identity[T], identity[U])
}

object BiConverter extends LowPriorityBiConverterImplicits {
  implicit def identityConverter[T]: BiConverter[T, T, T] = new BiConverter[T, T, T](identity, identity)
  implicit def firstAsSecond[T, U](implicit conv: T => U): BiConverter[T, U, U] = new BiConverter[T, U, U](conv, identity)
  implicit def secondAsFirst[T, U](implicit conv: U => T): BiConverter[T, U, T] = new BiConverter[T, U, T](identity, conv)
}

Then (some sample code):

abstract class Fruit
class Apple extends Fruit
class Banana extends Fruit

def main(args: Array[String]) {
  val int = (1 > 2) ? 5 / 6 // Int is inferred
  val fruit = (1 > 2) ? new Apple / new Banana // Fruit is inferred
  val double1 = (1 > 2) ? 5 / 5.5 // Double is inferred
  val double2 = (1 > 2) ? 5.5 / 5 // Double is inferred
}
Jean-Philippe Pellet
  • 59,296
  • 21
  • 173
  • 234
9

Here is my version just cause I'm curious. I wouldn't really use this...

I chose low priority operators. ^ will bind first, then |?. I use the fact that tuples are covariant to infer the type of the result.

case class TernClause[T](t: T) {
  def ^[U](u: U) = (t, u)
}
case class Tern(b: Boolean) {
  def |?[U](tuple: (U,U)) = if (b) tuple._1 else tuple._2
}

implicit def toTern(b: Boolean): Tern = Tern(b)
implicit def toTernClause[T](t: T): TernClause[T] = TernClause(t)

(1 > 2) |? "hi" ^ "abc"
// java.lang.String = abc

(1 > 2) |? 5 ^ 6.0
// AnyVal{def getClass(): java.lang.Class[_ >: Double with Int <: AnyVal]} = 6.0

Another example showing how operator precedence works together:

3 > 2 |? 5 - 1 ^ 6.0 + 1
// AnyVal{def getClass(): java.lang.Class[_ >: Double with Int <: AnyVal]} = 4

Probably some work needed to ensure the unused branch does not get evaluated.

Just food for thoughts: note that type inference does the right thing when calling a function. Would a less flexible syntax work for you? It's really a lot simpler...

class BooleanEx(b: Boolean) {
  def ?[U](onTrue: => U, onFalse: => U) = if (b) onTrue else onFalse
}

implicit def toBooleanEx(b: Boolean): BooleanEx = new BooleanEx(b)

class A
class B extends A

(1 > 2) ? ("hi", "abc")
//res0: java.lang.String = abc
(1 > 2) ? (5, 6.0)
//res1: Double = 6.0
(1 > 2) ? (5, 6)
//res2: Int = 6
(1 > 2) ? (new A, new B)
//res3: A = B@1e21540

Also, this is available in scalaz but they name it fold:

import scalaz._
import Scalaz._
(1 > 2) fold (5, 6.0)
//res0: Double = 6.0
huynhjl
  • 41,520
  • 14
  • 105
  • 158
  • Nice, but the inferred return type is still `AnyVal` instead of `Double` as it would be in a regular `if`… – Jean-Philippe Pellet Oct 30 '11 at 06:58
  • For this simpler version, `(1 > 2) ? (BigInt(3), 6)` returns `Any = 6`, whereas Jean-Philippe's version returns `BigInt = 6` – Luigi Plinge Oct 31 '11 at 00:30
  • @LuigiPlinge true, I thought the extra complexity wasn't worth it, but I gotta give credit, I didn't realize that JPP's solution was able to leverage implicit conversions like `BigInt.int2bigInt`. +1. – huynhjl Oct 31 '11 at 00:49
2

I've been playing around with @Jean-Philippe's solution, and made a couple of additions to allow the chaining of operators. (Well I could have just left it as it is and used parentheses, but where's the fun in that?) There's probably a better way to do this, so suggestions for improvements are welcome.

implicit def boolToTernary(cond: Boolean) = new {
  // operator name changed
  def |? [T](f: => T) = if (cond) Ternary(Some(f)) else Ternary[T](None)
}

case class Ternary[T](o: Option[T]) {
  def or [U, That](f: => U)      (implicit conv: BiConverter[T, U, That]): That = o map conv.toThat1 getOrElse (conv toThat2 f)
  // overload added
  def or [U, That](t: Ternary[U])(implicit conv: BiConverter[T, U, That]): Ternary[That] = o match {
    case x: Some[_] => Ternary(o map conv.toThat1)
    case None       => Ternary(t.o map conv.toThat2)
  }
}

I changed the operator names: the one in the Ternary class needs to be lower priority, but the one in the implicit def also needs to be low priority, and | has the lowest priority other than alphanumerics.

Also I added an overload, so that we can take another Ternary clause.

Hence

1 > 2 |? 4 or 4 > 6 |? 8.0 or 10  //look, no parentheses!
// Double = 10.0

1 + 1 < 3 |?
  4L or
  4 > 6 |?
    8 or BigInt(10)
// scala.math.BigInt = 4

Cool or what? :) Who needs if / else anyway?

Luigi Plinge
  • 50,650
  • 20
  • 113
  • 180