de.velopmind | The Det about Programming

April 25, 2012

y ( is ( 6 afraidOf 7 ) )

Filed under: Scala, Uncategorized — de.velopmind @ 5:49 pm

Or: What happens when a simple number joke meets a bored Scala developer …

Save the following code into a file, e.g. named Fears.scala.

type Reason = () => String

class ReasonedState(val state:Boolean, val reason:Reason)

case class True(why:Reason)  extends ReasonedState(true, why) {
   override def toString() = "yes"
}
case class False(why:Reason) extends ReasonedState(false, why) {
   override def toString() = "no"
}

class Fears(value:Int) {
   def afraidOf(other:Int) = (value,other) match {
      case (6,7) => True (() => (7 to 9).toList.map(_.toString).reduce(_+" "+_))
      case _     => False(() => "nothing to fear")
   }
}

implicit def numbersFears(nu:Int) = new Fears(nu)

def is(rs:ReasonedState) = rs
def y (rs:ReasonedState) = rs match {
    case rs:True => "because "+rs.reason()
    case _       => "wrong question"
}

Then open the Scala REPL in the same directory as the file you saved and type:

scala> :load Fears.scala

Now type:

scala > y ( is ( 6 afraidOf 7 ) )

…and enjoy the result.

Tip: If you don’t already know it, read the input and the result aloud (in english).

Advertisements

1 Comment »

  1. fantastic.

    Comment by Aaron Masino — April 27, 2012 @ 10:12 pm


RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Create a free website or blog at WordPress.com.

%d bloggers like this: