Pattern matching arrays

This was sitting among drafts for quite some time. But I should be studying for exams right now so normally I find lots of stuff to do.

I friend told me about some weird behavior he found in scala. You can get a head and a tail of an array but if you try to pattern match for both at the same time you get a compile or runtime error. This seems interesting. Time to investigate!

val a = Array(1,2,3)
a match { case x::xs => x } //doesn't compile
:9: error: constructor cannot be instantiated to expected type;
found : collection.immutable.::[B]
required: Array[Int]

You can probably tell from the compile error what am I doing wrong. But I’m not giving it away yet. Let’s try to create a Seq and then match.

a.toSeq match { case x::xs => x }

Success! This compiles. But it’s too early to celebrate since it fails at runtime.

scala.MatchError: WrappedArray(1, 2, 3) (of class scala.collection.mutable.WrappedArray$ofInt)

Have you figured out yet? :: is a constructor and extractor(case class really) for List[_]. And for List only!(because it’s a case class). It extends Seq so you can pattern match and it will compile but it wont match at runtime.
Type signatures look like this

def apply[B](hd: B, tl: List[B]): ::[B]
def unapply[B](x$0: ::[B]): Option[(B, List[B])]

It should be clear this unapply won’t match a WrappedArray. But we can do a workaround! Write our own extractor that gets head and tail from an arbitrary Seq. If I remember correctly such extractor is not in the standard library since it’s performance would be unpredictable(depends on the underlying Seq).
But we know what we’re doing so lets write it anyway.

object +:{
  def unapply[B](seq: Seq[B]) =
    try {
      Some(seq.head, seq.tail)
    }
    catch {
      case _ => None
    }
}
 
//now we can use it like this
a.toSeq match { case x +: xs => (x,xs) }
//(Int, Seq[Int]) = (1,WrappedArray(2,3))

And it gives a match error for empty arrays. Fair enough. This is one of the reasons I like scala; it let’s me extend the language to my heart’s content. Please note that this is more of an example that real world use. For one off pattern matching this is a bit of an overkill. .head and .tail do the job adequately.

Enhanced by Zemanta
Share on Twitter

750 words

Writing

Writing (Photo credit: jjpacres)

This week I felt the impulse to express myself multiple times. I felt like writing. Being a bit sentimental I opened up a notepad I got from my girlfriend as a birthday present and began a brain dump. A stream of consciousness. But my handwriting is painfully slow. This means I had time to do reformatting and rewording in my mind. Sot this was definitely not a brain dump. I wasn’t expressing my thoughts directly but rather doing some writing – I don’t know how to put this subtle(but important) difference better. And after 2 small(<A5 format) pages I gave up. I kinda wanna keep a journal  but this is too much work for too little return.

Enter interwebs

Then I remembered this awesome site 750words.com. I’ve seen it before but I didn’t feel the need to use it. Now it somehow hopped back into my mind. It is meant just for just the thing I need – writing unprocessed brain dump. Apparently this is a thing amongst writers and they call it Morning Pages because it’s usually done in the morning. I’m only using it for two days so not much experience here but it just feels good. Yesterday I wrote in the evening and it was more reporting/diary style and today I wrote in the morning(two hours after I got up) and it was more reflecting style; expressing my thoughts.

Why not just use Office(I like LibreOffice as I don’t have and Windows machines) you ask? I gives you space to type anything without putting it on the internet. There is something special about just opening a page and writing. Like picking up a notebook… It handles days for you. And it’s suposed to be private. And all your data is on all machines. Because it’s, you konw, on the Internet. This means I don’t need to spend time fussing over technical details and I can just write. And it also looks kinda beautiful.  There’s a word counter too, the idea is to write at least 750 words, because this is enough you cannot just blurt it out but have to dig into yourself a bit. But it’s not to much. And the idea is also to do this every single day to get into the habit. So you get points and badges(a bit silly but nice) and also compete in challenges(to see if you can hold out an entire month).

Analytics

The super duper awesome part is analytics. It uses some fancy machine learning to analyze what you write. For a started you get a feedback on your typing(something I wanna improve). But then things get nice. I tells you how you feel and what are you concerned about. If you are writeing more extroverted or introverted, positive or negative, in wich time are you oriented, most used words and more. And the best of it: it is correct. At least for my two entries so far it got me figured out. It points out stuff you wouldn’t normally think about.

And you also get archiving and over time analytics. And of course you can export your data.

The only downside is I have to type in English which isn’t my primary language(or should I say mother tongue). But wit internet I grew accustomed that my typing is mostly English so it feels natural. It’s about as weird for me to type in Slovene as it is to hand-write English. That is not-really-weird-but-not-very-natural(Sorry for the hyphen abuse but I feel this should be one word). So I don’t mind, it’s totally worth it.

Give 750words a shot. It only takes a few minutes a day.

Enhanced by Zemanta
Share on Twitter

Union types in scala

I’ve done some research  a wIhile ago on union types and found a nice implementation by Miles Sabin but it only works for declaring types of function parameters. And you can also do this with with type classes.

What do I mean with “only function parameters”? In “everything is a function” kind of view there are three places to put types

  1. function parameters
  2. value(val or let binding in haskell and the like)
  3. function return type

Even though Miles’ encoding with Curry-Howard isomorphism is ingenious it only applies to point 1. Let’s fix that! Oh yeah you could also use Either but that adds up boilerplate(even with implicits!) and packing. And I want my union types unboxed.

Enter type tags

I first saw this idea in Scalaz and immediately clicked with me. The idea is to combine structural types with existing types. You don’t touch the value, just enhance the compile-time type with a tag. Structural types are, well types that care about structure not name(JVM has nominal type system) and (sadly) use reflection to do stuff at runtime. You can even use it do do clean-ish method invocation with reflection.

type HasFoo = { def foo(): Bar }
(a:Any).asInstanceOf[HasFoo].foo()
//or even
(a:Any).asInstanceOf[{def bar: Int}].bar

But at compile-time they play along very nicely. Only concern if you don’t want reflection is not to use anything at runtime. But you can use type members! They only appear at compilation so this works out perfect.

From scalaz

type Tagged[U] = {type Tag=U}
type @@[V,T] = V with Tagged[T]
 
type ExampleTaggedType = Foo @@ Bar
 
implicit class Taggable[A](value: A){
  def tag[T] = value.asInstanceOf[A @@ T]
}
 
val a = SomeType @@ Baz = someValue.tag[Baz]

Tagged is just a conversion between a regular generic and a structural type with Tag member Type. This allows you to define @@ – that’s simple too: it takes the type and mixes in the structural tag. Foo @@ Bar now means type Foo but with tag Bar, the only difference between them is that values of type Foo @@ Bar now have a member type Tag that will equal Bar. And I threw in an implicit for easier tagging.

Subtyping with existentials

We need one more tool to get everything in place – subtyping. I mean subtyping as in “if A is subtype of B and C is subtype of D then A @@ C is also subtype of B @@ D”. Technical term for this is covariance. And with classes is done by simply adding pluses to type signature like type @@[+V,+T]=… but this doesn’t work for types. You get a compile error as type parameters are used in non-covariant positions. Luckily we can work around this with use-site subtyping. Instead of using type A @@ B you can use X @@ Y for some types X and Y. Quite literaly with this syntax

type Something = X @@ Y forSome {type X; type Y}

And these are existential types. Because X and Y have to exist. Simple. There is some sugar with _(as usual) but it doesn’t work at all places; let’s not get into detail.

Either, or should I say Union

Now that we have the necessary foundation lets take a look at making unboxed version of Either from scala standard library. Conversion is pretty simple: instead of boxing into Left and Right, tag with Left and Right. And instead of being of type Either a value will be some type tagged with Either. I first implemented this with my type hierarchy only to realize I reimplemented(without real functionality) Either.

type Or[A,B] = @@[_, _ <: Either[A,B]]
 
implicit def any2taggedLeft[A](a:A): A Or Nothing = a.tag[Left[A,Nothing]]
 
implicit def any2taggedRight[A](a:A): Nothing Or A= a.tag[Right[Nothing,A]]

There is Or type(intended for inline use) that equals something tagged with something that’s a subtype of Either[A,B] – this is anonymous use site subtyping, a workaround for not being able to make tags covariant. And that’s pretty much all there is to it. The two implicits are just for automatic tagging so you can use regular types and compiler will tag them for you to type check union types.

And when this code compiled and worked I started cheering. Let me replace my current lack of enthusiasm by use examples to let you fully gasp the implications on your own.

def id[A](a:A):A=a //a helper for testing parameter types
 
val a: Int Or String = 1
val b: Int Or String = "hi"
val c: Int Or String = 1.2 //does not compile
 
id[Int Or String](1)
id[Int Or String]("hi")
id[Int Or String[(1.2) //does not compile
 
def f(n: Int): Int Or String = 
  if(n>0) 
    n: Int Or String 
  else 
    "n is negative": Int Or String

As you can see all three requirements from the intro are satisfied while keeping values unboxed. There are some rough edges unfortunately.

Compiler refuses to insert tags without explicit type annotations that inform it to insert implicit conversions. Which is kinda weird because it work for regular Either. Still looking into that.

And the real letdown is pattern matching. You can’t match against types…compiler just complains about these types not being possible. And it’s kinda right since String isn’t in fact a subtype of Or[String,Int]. Luckily there’s a workaround that’s not too ugly.

(a:Any) match { 
  case _:String => "string"
  case _:Int => "int"
}

I have an idea how to solve both issues but it involves forking scala standard library and is thus (much) less portable.

Of course if anyone has an idea how to convince the compiler to accept (fake) subtypes or how to steer type inference please let me know.

Enhanced by Zemanta
Share on Twitter

Generic singletons through dependent method types

Ever tried to write a generic singleton? It’s an oxymoron of a sort. But sometimes my brain dreams up funny concepts to solve the problem at hand. Sadly I cannot remember what I wanted to use them for. Anyway I think I just made all the methods generic and solved it this way. But this doesn’t really express the notion of one entity that’s agnostic to type of the parameters. With generic methods you get a bunch of disconnected units – at least that’s the picture in my head.

General

Challenge Accepted!

Challenge Accepted! (Photo credit: pierreee)

So we’ve established that generic singletons are just a silly idea, now let’s try to implement it – you know “Challenge accepted!” style.

object Singleton[A] { //error: ';' expected but '[' found.
  def id(a:A) = a
}

Luckily this naive approach does not compile. Try it.

class Singleton[A]{
  def id(a: A) = a 
}
 
def Singleton[A] = new Singleton[A]

But this is not a singleton anymore as there is a new instance created everytime.

object Singleton{
  class Instance[A] private[Singleton] (){
    def id(a: A) = a 
  }
 
  private[Singleton] val cache = 
    collection.mutable.HashMap[Class[_],Instance[_]]()
  def apply[A]()(implicit m: Manifest[A]) = 
    cache.getOrElseUpdate(m.erasure, new Instance[A]).asInstanceOf[Instance[A]]
}
 
//use as
Singleton[Int].id(1)
 
//and some sugar
def singleton[A:Manifest] = Singleton[A]()
 
//now use like
singleton[String].id("hi")

Didn’t bother with thread safety. And dragging around Manifest just for caching is a bit of a pain, luckily elevated by context bounds.

Type specific

That worked for classes that don’t bother about the generic types…what if we want specific behavior per type? Type classes. (I mentioned that once). A trait for general interface and objects for specific types. Magic lies in making these objects implicit and having a method that gives you the right one!

trait Singleton[A]{
  def f(a: A): A
}
 
implicit object IntSingleton extends Singleton[Int]{
  def f(n: Int) = n + 1
}
 
implicit object StringSingleton extends Singleton[String]{
  def f(s: String) = "Hello " + s
}
 
def Singleton[A](implicit s: Singleton[A]) = s
 
Singleton[Int].f(1) // == 2

Specific functionality

Now let’s add a little twist.

implicit object IntSingleton extends Singleton[Int]{
  def f(n: Int) = n + 1
  def g(n: Int) = n - 1
}
 
//this line doesn't compile
Singleton[Int].g(1)

and it doesn’t compile for a reason. Static type of returned from Singleton[Int] is Singleton[Int]. And there is no method g defined in trait Singleton. But we are sure it exists. We could call IntSingleton directly but this makes whole Singleton abstraction worthless. Luckily for us scala 2.10 has a feature called method dependent types. To my best understanding this means support for return types that depend on the type of parameters. And here we want the type to reflect which instance is being returned. Nothing suits the job better as singleton types. Singleton type is a type that has only one value. So an object A will be of type A.type. This type is worthless for inference but great when you’re doing the type tags. We just need a little fix

def Singleton[A](implicit s: Singleton[A]): s.type = s

This method will return the correct instance along with it’s type while giving you a nice abstraction of type constructor.

 

Enhanced by Zemanta
Share on Twitter

Learning Scalaz part 1

I’ve finally decided to dig into scalaz as I feel confident with type and category theory. I’m using eed3si9n’s adventure heavily, just to give credit. This kinda works like my journal and hopefully helps somebody else. I believe in “learn by teaching” motto. So let’s dig in.

Typeclass 101

This is a very brief recap. Type this awesome video form marakana for a lengthy introduction. classes in scala are represented with higher-kinded trait and implicit instances of for specific types. Functions take these as implicit parameters or express them as context bounds. Quick sample: a trait that defines a special operation on a type.

trait Special[A]{
  def special(a:A): A
}
 
implicit object SpecialString extends Special[String]{
  def special(s: String) = "hello " + s
}
 
//won't compile if there's no instance of Special
def foo[A](a: A)(implicit special: Special[A]) = ...
 
//can be sugared to
def foo[A: Special](a: A) = ..

You could read “A: Special” as A is of type Special. Kinda makes sense(but not really) as the structure is called type class. But this actually desugars into version with implicit evidence.

Context bound implicit conversions

Implicit conversions are cool, but they’re even cooler when they’re context bound. See classes can be polymorphic and emulate higher order functions with something called strategy pattern. If a function’s behavior is defined by an object(or function value) it’s essentially polymorphic. As a bonus if we use type classes this polymorphism is user-extensible even without access to source.

If we want to use out Special now the syntax is quite cumbersome but an implicit can solve this

//now
implicitly[Special[Foo]].special("foo")
 
//we want
"foo".special
 
//solution
implicit class SpecialOps[A](a: A)(implicit ev: Special[A]){
  def special = ev.special(a)
}

This will lift any type for which there is an instance of Special. It’s a convenient way to get OO style(like in scala collections) while actually implementing it with type classes. You can – at type level – express the relation of all types that have the map method; there exist a Functor instance for each of them.

This post didn’t feature an of scalaz really, but type classes and this implicit mechanism are two things I found essential to my understanding.

Share on Twitter

Monadic IO with ScalaZ

I just recently scratched the surface with scalaz. Think of it as an additional standard library for scala that’s FP oriented. It provides a bunch of type classes, instances for pretty much everything, some fancy data types, pimps(Pimp My Library) for standard library collections, actor implementation and probably some stuff I’m not aware of. I could really use a “map of scalaz” – but I’ll probably dive into source and scaladoc anyway.

One fancy feature that’s not noted on their Google Code page is IO monad implementation. I’ve

Denali Landscape

Real World Tm – the thing your programs have to interact with (Photo credit: blmiers2)

written a bit about monadic IO in My take on monads but let’s recap. IO monad is a data structure that represents a tiny language which let’s you describe and compose IO actions without actually performing them – allowing you to keep your functions pure and compose/reuse better.

Monadic HelloWorld with scalaz

I’ll be using SBT to manage dependencies(scala and scalaz) so let’s create a project. We just need build.sbt file with this content(or use my template: g8 edofic/scalaz-empty)

scalaVersion := "2.9.2"
 
resolvers += "Scala Tools Snapshots" at "http://scala-tools.org/repo-snapshots/"
 
libraryDependencies += "org.scalaz" %% "scalaz-core" % "6.0.4"

and then run “sbt console” to get a REPL with scala 2.9.2 and scalaz 6.0.4. Pretty useful. Let’s get to code now.

import scalaz._
import Scalaz._
import scalaz.effects._
 
val greeter = println("hello world").pure[IO]
 
//scalaz provides a helper for that so we can write
val greeter2 = putStrLn("hello from scalaz")
 
greeter.unsafePerformIO

First a bunch of imports to get scalaz magic and then the crucial line. Scalaz provides an implicit conversion which allows us to call .pure[A] on every value. This gets Monad[A] instance from implicit scope and lifts the value into the monad. It’s a type class way (think dependency injection) to invoke monad “constructor”, a simple sample

scala> "hi".pure[Option]
res0: Option[java.lang.String] = Some(hi)

Scalaz also provides a helper putStrLn(and many more, including readLn) for more succinct code. Note that lifting our println(by hand) does call by name(lazy evaluation) so println is not actually invoked yet! To perform the IO action you need to explicitly call unsafePerformIO. Intentionally verbose and scary name to make you think twice where you perform your side effects.

But printline is not that interesting. Let’t take a look at input. Type of readLn is IO[String] and it’s perform method returns a String. Notice that IO is a monad so you can do map and flatMap on it. For example readLn.map(_.toInt) gives you and action that will read and parse an integer returning you something of type Int. FlatMap is more interesting because it gives you composition. FlatMapping another IO action will execute actions in sequence giving last action access to previous actions’ return values via closures. That’s referred to as monadic style. It’s basically a pure way of doing imperative programming.

A bit more involved example

for{
  _    <- putStrLn("who are you?")
  name <- readLn
  _    <- putStrLn("hello " + name)
} yield ()

And a tiny calculator showing off composition

val inputInt = for{
  _ <- putStrLn("enter an integer")
  raw <- readLn
} yield raw.toInt
 
val adderIO = for {
  a <- inputInt
  b <- inputInt
  _ <- putStrLn((a+b).toString)
} yield ()
 
//and to run it
adderIO.unsafePerformIO
Enhanced by Zemanta
Share on Twitter

Null-coalescing(??) in scala

I was doing my homework today(yes I am aware I should be enjoying myself on 30th December)

The supermassive black holes are all that rema...

Null reminds me of black holes.

and rad some problems with concatenating possibly null strings in LINQ. Quick trip to StackOverflow and I find out C# has some funky operators that solve this in a (sort-of) clean way.

var outputString = input1 ?? "" + input2 ?? "";

I like type inference so I use var’s extensively – please don’t judge me. What this does is concatenate input1 and input2 substituting null values with empty string. In scala you would write something like

val outputString = Option(input1).getOrElse("") + Option(input2).getOrElse("")

but that’s verbose and ugly. Wrapping and unwrapping to get some added semantics of the Option factory(returns None for null). But you shouldn’t have nulls in the first place if you’re using scala. That’s what Option is for! Enough ranting, let’s implement this ?? operator in scala.

implicit class NullCoalescent[A](a: A){
  def ??(b: => A) = if(a!=null) a else b
}

Yup. That’s it! You only need this in scope and of you go writing code C#-style.

scala> "hi" ?? "there"
res0: String = hi
 
scala> (null:String) ?? "empty"
res2: String = empty

Note the type of b parameter in ?? method. It’s => A. By name evaluation. This means our new operator behaves properly and only evaluates right hand side if value is in fact null. This lets you for example log unexpected nulls while substituting for default value

val key = valueFromUser ?? {
  log("key is null!"}
  defaultKey
}

This works because scala let’s you do side effects like that.

I just wanted to add one reason why I love scala is this easy way of defining structures that feel like they’re part of the language while being nothing more than just libraries.

Enhanced by Zemanta
Share on Twitter

Setting up for better Scala development on Android

Image representing Android as depicted in Crun...

Image via CrunchBase

I did a tutorial how to set up everything using IntelliJ a while ago. I still think IntelliJ IDEA is awesome and you should use it(it has a free and open version) but I’ve found a better way. No more clicking around in wizards…it’s config file time. Relax – it’s quite simple.

I recommend installing the Typesafe-stack. It gives you the two tools listed below in nice packaged form with updates. And that’s about it. I’m quite fond of package managers => one place to update everything.

SBT

Simple Build Tool. Exactly what the name says. Simple. But boy it’s powerful. And it has a plugin for doing android development. Batteries included(managing emulator & packaging all from one place). And it prefers convention over configuration. Great. All this leads to quick results.

Giter8

Maven has archetypes and that’s a great feature since it enables you to just start developing your application without messing with build settings to get the damn thing to compile. SBT doesn’t have that. But there’s a third-party tool that does something possibly even better. Yes, giter8 or g8 for short(that’s the command line too). A tool that fetches templates from github(or any other git repo in recent versions) asks you for few parameters and creates a project for you. Super simple to use and not that hard to create your own templates.

Let’s get cracking

Use g8 to create an app and configure it

g8 jberkel/android-app

Template for Android apps in Scala 

package [my.android.project]: com.edofic.demoapp
name [My Android Project]: DemoApp
main_activity [MainActivity]: 
scala_version [2.9.2]: 2.9.1
api_level [10]: 
useProguard [true]: false
scalatest_version [1.8]: 

Applied jberkel/android-app.g8 in demoapp

This is from interactive session. Stuff after colons is my input…eh I won’t try to  explain. Just try it. Explanation on parameters is in place though. Template is from the author of the plugin; I used default activity name because I don’t care. Scala version is 2.9.1 because that’s what’s preinstalled on my phone(more on that later) and ProGuard is off to exclude scala standard library from the dexing step. See SBT is know that scala standard library doesn’t fit through dexing and excludes it. But it does some magic too. Whole packaging process is 2-3x than ant/maven/eclipse/idea. And again twice faster if you use 2.10(RC5) instead of 2.9.x. It gets under 10s on a good machine. Sadly my laptop is not that fast so I use predexed scala library to get under that magical 10s. Essentially I’m telling the compiler not to bother with the library and take care of it myself. There are two ways of doing that. Note that you only need to do this once per device.

Patching the device/emulator

Modify boot classpath and add libraries. Some nasty bootimage manipulation for real devices. Simple script for emulator. What I use for most development. See here how to do it.

Shared libraries

This is how Google provides libraries for their maps API on android. There’s even an app on Play store that does that for you(requires root). More info on their github page. The downside is you need to include a few lines into your manifest(just development, you take it out for the release). I need to do more research on this – maybe gonna post a guide when I figure out how to install custom versions of scala like that.

Compiling and running

Here comes a quirk. Plugin doesn’t play nice with latest version of sbt. Fortunately sbt is capable of  running different versions without any hassle. You can provide “-sbt-version 0.12.0″ every time or create a project/build.properties with “sbt.version=0.12.0″ in it(or use my template – g8 edofic/android-app). This starts up sbt and does compile-deploy-start operation.

sbt
....
android:start-debug

Checkout the plugin page for list of available commands.

Why SBT?

I’ve only been converted recently but I’ve already found a bunch of nice stuff I can do now. Firstly..dependency management. Now it’s a breeze. Typed resources via source generation – no more casting and exceptions on findViewByID(see plugin github page for more). You can easily plug in your own generation stuff too. And there’s nifty feature I really like: continuous compilation. In sbt console you write “~ compile” and sbt will run incremental compilation triggered by file changes.

Integrating with IDEA

Some people prefer programming in a text editor. I don’t. So I like IDE integration. Luckily there’s an SBT plugin that generates IDEA project for seamless interaction. You can even run SBT console inside idea for minimal window switching. Usage(from plugin github page):

Add the following line to ~/.sbt/plugins/build.sbt or PROJECT_DIR/project/plugins.sbt
addSbtPlugin("com.github.mpeltonen" % "sbt-idea" % "1.2.0")

And then you can use “gen-idea” command in sbt console to generate idea project files.

Integrating with Eclipse

Same story goes for eclipse. Plugin can be found here. To use it:

Add sbteclipse to your plugin definition file. You can use either the global one at ~/.sbt/plugins/plugins.sbt or the project-specific one at PROJECT_DIR/project/plugins.sbt:

addSbtPlugin("com.typesafe.sbteclipse" % "sbteclipse-plugin" % "2.1.1")

and to generate project file you use “eclipse” command in sbt console.

Links

Gathered for conveniance

Enhanced by Zemanta
Share on Twitter

Chaining implicit conversion in scala

Today I was hanging in the #scala IRC channel and somebody came along(forgot the nick, sorry) and asked about some compilation error. I deduced he was trying to chain implicit conversions. And this doesn’t work. Else compilation would take forever and would also compile some wrong code by inserting long strings of implicits. But then somebody else responded(I think nick started with d) and gave a solution to implicit chaining. But I’m not giving it away yet, you’ll have to read a bit more.

The problem

Let’s say I have some classes that just add semantics to values(think labeled boxes)

case class Foo(a: Int)
case class Bar(b: Int)
case class Baz(c: Int)

And because they look similar we may want to do some implicit conversion. Let’s say that that’s needed is conversion from Bar to Foo and from Baz to Bar.

implicit def bar2foo(bar: Bar) = Foo(bar.b)
implicit def baz2bar(baz: Baz) = Bar(baz.c)

On a level this also implies that Baz can be seen as Foo. But when you try it

println(foo.a)
println(bar.a)
println(baz.a)

you get a compile error

Implicits.scala:18: error: value a is not a member of Implicits.Baz
println(baz.a)
^
one error found

The solution

As said, scala compiler doesn’t try to traverse the graph of implicit conversions and therefore doesn’t figure out how to insert needed conversions here. But here lies a handy catch. What if the conversion wasn’t from Bar to Foo but from something Bar-like to Foo. Then the compiler would know that this chaining is intended and is (probably) not a dead end. Good news: scala lets you express that. It’s called a view bound. You make the method generic and limit input type to something that can be seen(implicitly converted to) as a Bar. Here’s the code.

implicit def bar2foo[T &lt;% Bar](bar: T) = Foo(bar.b)

All the magic lies in the <% operator. That’s the view bound. When you type baz.a the compiler sees that a property is available on the Foo class and that there’s an implicit conversion to Foo from something Bar-like. Fortunately there’s a conversion from Baz to Bar in scope so it can invoke the method. Inside the method it tries to get the b property from baz but it’s not available. So it checks the conversions and sees that a conversion from Baz to Bar exists in the scope and it satisfies the need for b. It inserts this conversions and compilation happily chucks along.

Nest all the implicit conversions!

Nest all the implicit conversions!

Please don’t do that. Implicits can make code hard to read even without nesting. So use with care. Scala is a very powerful language but great power comes with great responsibility.

Enhanced by Zemanta
Share on Twitter

My take on monads

Rubik's Cube, color scheme modified, with shad...
Rubik’s Cube, color scheme modified, with shadow and reflection (Photo credit: Wikipedia)

A monad is just a monoid in the category of endofunctors, what’s the problem? I like this quote. When you find it funny you probably understand what a monad is. And I’ll try to explain it.

Learning this stuff was kinda hard for me because I’ve never encountered category theory so the concepts seemed strange to me. Now I’ll try to share my intuition and hopefully help somebody. Pro tip: read many different “monad tutorials”. Number of these articles is apparently exponential function so you won’t have trouble finding them. I’ll try to deliver a more pragmatic approach so instead of formally correct definitions I’ll do some hand-waving to produce something more useful.

Types(and kinds)

Instead of talking about categories and morphisms let’s focus on types. That’s what scala is about right? 

We are talking about general concepts and transformations(functions) here so we’ll need generics. The other point is we want to have different semantic for different occasions. The most obvious way to do that is to write different generic wrappers. More formally: type constructors. Stuff like Option[A], List[A], Future[A], Box[A]… These are not usable types yet(roughly speaking) as scala doesn’t support raw types like java. You need to provide type parameters to obtain types like Option[Int], List[Option[String]]… We say that such types are higher kinded types. See a kind is to type what a type is to value. Remember that, it’s a great analogy(from Daniel Spiewak). So Option, List and other types we are currently interested in are of kind * -> *. This reads “type to type”. It takes a type parameter, say Int, and produces a type, in this case Option[Int].
It should slowly become clear that we can write a higher kinded type to add custom semantics to any raw type.

Functors

Function maps from value a to value b. A functor is a higher kinded type that allows to lift functions and operate on boxed values. This means function does not need to be aware of any additional semantics you put in place. In other words, a functor is something that has a proper map function.
trait Functor[F[_],+A]{
def map[B](f: A=>B): F[B]
}
So the functor “knows” about the type of box(F[_] is scala syntax for * -> *) and takes type parameter. Map must then be implemented to lift a function into this context. A sample usage. Re-implementing Option type
sealed trait Opt[+A] extends Functor[Opt, A]

case class Som[A](value: A) extends Opt[A]{
def map[B](f: A=>B) = Som(f(value))
}
case object Non extends Opt[Nothing]{
def map[B](f: Nothing=>B) = Non
}

Option adds semantics of missing value. Box may be full or empty. And computations must succeed in any case. Operations on empty option(Non) just return an empty box while if there is a value you apply the function to the value and box it up.
Most know application of map is probably on List. It transforms the List[A] to List[B] by applying the function to every element.
Code above is in fact an endofunctor. Endofunctor is something that maps from category A to category A. A in this case is the category of types. There are links at the bottom for more explanation.

Typeclasses

This comes from functional languages(I’ve learned it from Haskell first). It’s a simple concept in it’s heart. Ad-hoc polymorphism. Add functionality and semantics to existing types without changing them. You do that by creating a type class and instances for types you want to “extend” the type class. First of all type class has nothing in common with classes. I’ll rewrite the Opt type sample with type classes to make an example.
trait Functor[F[_]]{
def map[A,B](fa: F[A])(f: A=>B): F[B]
}

sealed trait Opt[+A]
case class Som[A](value: A) extends Opt[A]
case object Non extends Opt[Nothing]

implicit object OptFunctor extends Functor[Opt]{
def map[A,B](opt: Opt[A])(f: A=>B) = opt match {
case Non => Non
case Som(a) => Som(f(a))
}
}
you pull the Functor instance from the implicit scope implicitly[Functor[Opt]] or do view bounds
def functorId[F[_] : Functor](fa: F[_]) = fa

here functorId is identity function that doesn’t compile if functor instance doesn’t exist for it’s argument.

Monoids

I’ve included type classes because monoids are much easier expressed through them. Object oriented way gets messy. You can try. Or better – prove me wrong, I’ll be delighted. 
So a monoid is something that can be added togheter or combined in a way. That’s it. Oh and it needs an identity element. Let’s express that as a type class
trait Monoid[M]{
def id: M
def dot(a: M, b: M): M
}
and an instance for Int with example usage
implicit object IntSumMonoid extends Monoid[Int]{
val id = 0
def dot(a: Int, b: Int) = a+b
}

def combine[A](xs: List[A])(implicit monoid: Monoid[A]) =
xs.fold(monoid.id)( (a,b) => monoid.dot(a,b) )
// combine(List(1,2,3)) == 6
You could easily do multiplication instead by setting id to 1 and replacing + with *.

Monads

Let’s stay with options and lists for a bit. What if you have a function f that returns an option(f: A=>Option[B])? If you map it over an option you get Option[Option[B]] or even more levels. 
You can deal with this by pattern matching…
def twoLevels[A,B](o: Opt[A])(f: A=>Opt[B]) = o match {
case Non => Non
case Some(value) => f(value)
}
and this produces the desired result. Same goes for list. You get into situations where you want List[A] but you got List[List[A]]. You can solve this by flattening the list(List has method flatten but let’s demonstrate it here)
def flatten[A](xss: List[List[A]]): List[A] = xss match {
case Nil => Nil
case ys::yss => ys:::flatten(yss)
}
Again pattern matching. What do these two got in common? You do something depending on the current value, execute the transformation(or not) and do something with the output. Looks very similar to the map function. And it is. On lists it’s just map and then flatten. Literally, you can write this with scala collections. But you can also do it in a single function. Scala calls it flatMap because of what it does. In haskell world it’s bind, we’ll see why in a minute. Here’s the type signature
trait Monad[M[_]]{
def flatMap[A,B](ma: M[A])(f: A => M[B]): M[B]
}

and an instance for our options. Note that Opt class did not need to be changed.

implicit object OptMonad extends Monad[Opt]{
def flatMap[A,B](ma: Opt[A])(f: A => Opt[B]): Opt[B] =
ma match {
case Non => Non
case Som(a) => f(a)
}
}

So why is this useful? If you have instances for collections(like in scalaz, standard collections do this in OO way) you can abstract away pattern matching and have very readable code. If you want do chain failable computations you just wrap them up in options and do a for expression. Like this

val result = for{
a <- Option(foo()) //foo can return null
b <- Option( bar(a) ) //bar can null too
c <- baz(b) //baz returns an option
} yield computation(c) // 'computation' never fails

What’s the type of result? Option of whatever computation returns. All failures are abstracted away.
Another good thing about flatMap is that it can express map and filter too. And that’s the reason for expressions from scala can be called monadic comprehensions.

Semantics

What’s so cool about sytactic sugar for pattern matching that it deserves such a special place? Monads are much more. Inside the for comprehension you have a custom programming language defined by the monad – the implementation of flatMap for given type. See, as long as it obeys some laws, the binding function can do pretty much anything. 
Let’s take a look at IO monad. There’s nothing scary here, you have ‘boxes’ describing IO actions. Let’s refer to these as contexts. And you can bind them together. If I have a ReadLine action and bind PrintLine action over it I’ll get a new action that will echo a line of text. Code would look something like this
for{
input <- ReadLine()
} yield PrintLine(input)
Note the initials. ReadLine and PrintLine are case class constructors. This expression just returns an IO action it doesn’t perform it – this is up to the caller. And so this expression is referentially transparent(always returns the same output for same input and no side effects). How does it work? Scala compiler actually desugars it into
ReadLine().flatMap( input => PrintLine(input) )

And flatMap is inplemented to join the actions together. See this is a great way to write functional programs that look imperative. In fact it’s the only way to do IO in haskell. Scala is more forgiving in this way.
What about futures? Future is a box that will hold a value sometime in the future. Scala 2.10 has them, Akka had them before and I think they’re in scalaz too. Heck even java standard library has them. Java one is not a monad though. Fun thing about monadic futures is that you can compose them.

for{
a <- futureA
_ <- futureB
c <- futureC
} yield a+c

This will yield a new future. It will wait on futureA to complete, take it’s value, wait for futureB(for side effects probably) and then wait on c for its value and on completion it will hold the sum. Different futures can be executed in parallel, even on different machines yet you can compose them and work with them in a sequential – very imperative – way. This works especially well with non-blocking IO since monadic comprehensions don’t block(if flatMap has a sane implementation).

Monoid in category of endofunctors

The joke from the beginning of course. Stop reading for a moment and think about it. It should make sense. If it doesn’t – read ahead.
Monad binds(combines) functions over a value in a context. And it adds some semantics while combining them. I tried writing some code
object OptTransMonoid {
def id[A] = (a:A) => Som(a)
def dot[A,B,C](f: A=>Opt[B], g: B=>Opt[C]) = (a:A) => {
f(a) match {
case Non => Non
case Som(a) => g(a)
}
}
}

You can see that I didn’t extend the monoid trait. I just couldn’t come up with a proper type parameter. Problem is that the two transformations we are trying to compose are of different types. So you need a generic method to remain typesafe. And a generic method cannot override a non-generic one on JVM. No matter how hard you try with type parameters. But the principle holds. A monad over M is a monoid over _=>M[_] (this is hand waving and not formally correct. _ stands for “some type” not Any).

More material

This concludes my brief overview. I hope you grew to like functional stuff. I’ve written a small IO monad implementation and usage demonstration below to give you a feel for real life usage.

IO Monad sample

trait IOAction[A]{ 
outer =>
def run: A

def map[B](f: A=>B) = new IOAction[B]{
def run = f(outer.run)
}

def flatMap[B](f: A=>IOAction[B]) = new IOAction[B]{
def run = f(outer.run).run
}
}
case object ReadLine extends IOAction[String]{
def run = readLine()
}
case class PrintLine[A](s: A) extends IOAction[Unit]{
def run = println(s.toString)
}

val greeter = ReadLine.flatMap(name => PrintLine("hello " + name))
greeter.run //reads a line and greets you

//with sugar(and nice to user)
val niceGreeter = for{
_ <- PrintLine("who are you?")
name <- ReadLine
_ <- PrintLine("hello " + name)
} yield ()
niceGreeter.run

Just a quick note. Monadic comprehension is this way because desugaring of <- is flatMap except for the last one where it's map. So to work around this you need to yield () instead of yielding the println action as this will map it instead of flatMap.

Enhanced by Zemanta
Share on Twitter