juan_gandhi: (VP)
Juan-Carlos Gandhi ([personal profile] juan_gandhi) wrote2013-01-23 07:37 pm

and more on type classes in Scala

This part is not exactly a theory of algebraic theories, but anyway.

Imagine we have a parametric class (e.g. List[X]) for which we would like to define methods that would only work if X satisfies certain conditions. E.g. define sum if it is a numeric type, or define flatten if it is some kind of sequence (Traversable[Y] would be enough). How can we accomplish it in Scala?!

Suppose we want to declare flatten
trait List[X] {
// bla-bla-bla

  def flatten[X <% Iterable[Y]] { ... } // no way, we already mentioned X; this one would shadow the previous one
// OOPS!
}


The trick would be to have an implicit transformation handy that transforms X into Iterable[Y] for some Y; and define it so that if X is actually some kind of Iterable, the implicit would be available, and otherwise not available.

Where can we find such a general transformation? The only thing that comes up to mind is an identity:

implicit def itsme[Y, X <% Iterable[Y]](x: X): Iterable[Y] = x

This would be enough in this specific case... but then we would have to define another one for numeric types, and so on.

We can go generic, and write something like this:
abstract class SafeToCast[-S, +T] extends Function1[S, T]
implicit def canCast[X <% Y, Y]: SafeToCast[X, Y] = new SafeToCast[X,Y] { def apply(x:X) = x }


Now we can define flatten, like this:
class List[X] { ...
  def flatten[Y](implicit transformer: SafeToCast[X, Iterable[Y]]) { ... }
}


All the conditions are satisfied now. Contravariance in the first argument and covariance in the second argument ensure that a subtype can be cast to its supertype... to be more precise, an instance of supertype can be substituted by an instance of subtype.

The only thing is that we can try to make the code more readable, by refactoring.

Step 1. Use the trick in Scala that binary operations can be written in an infix way, even for types. E.g. you can declare val map: (String Map Int) - this is the same as Map[String, Int].

sealed abstract class SafeToCast[-S, +T] extends Function1[S, T]
implicit def canCast[X <% Y, Y]: (X SafeToCast Y) = new (X SafeToCast Y) { def apply(x: X) = a }
...

class List[X] { ...
  def flatten[Y](implicit transformer: X SafeToCast Iterable[Y]) { ... }
}


Step 2. Rename the method, giving it a more "type-relationship" name: SafeToCast -> <:<.

sealed abstract class <:<[-S, +T] extends Function1[S, T]
implicit def canCast[X <% Y, Y]: (X <:< Y) = new (X <:< Y) { def apply(x: X) = a }
...

class List[X] { ...
  def flatten[Y](implicit transformer: X <:< Iterable[Y]) { ... }
}


That's the trick.

(if you have questions, ask; if you have corrections, please tell me)

[identity profile] ivan-gandhi.livejournal.com 2013-01-24 07:54 am (UTC)(link)
Скажем, Iterable[Y]?

[identity profile] xeno-by.livejournal.com 2013-01-24 08:06 am (UTC)(link)
Я бы в честь этого хотел бы отметить две техники, которые делаются возможными благодаря имплиситам.

Первая - то, что при помощи имплиситов можно разрешать или запрещать типы. Скажем, если ожидаемый тип результата вызова флаттена не подходит ни под один имплисит, то будет ошибка компиляции. Это отлично описано в посте.

Но есть еще и вторая. Если ожидаемый тип (pt в терминологоии тайпера) неизвестен, то имплисит серч позволяет его вывести!! Именно таким образом работает CanBuildFrom, позволяя мапу над строками возвращать строки, а мапу над листами - листы. И все это при помощи только одного определения функции map (в плане, достаточно определить map в базовом трейте коллекций и потом ничего нигде оверрайдить не придется - нужные типы будут выводиться автоматом для каждоо конкретного случая как надо).
Edited 2013-01-24 08:07 (UTC)

[identity profile] sassa-nf.livejournal.com 2013-01-24 10:23 am (UTC)(link)
а чё вот так: http://ivan-gandhi.livejournal.com/2213417.html?thread=28781865#t28781865 - хорошо бы, чтобы компилятор допонимал

[identity profile] ivan-gandhi.livejournal.com 2013-01-24 06:51 pm (UTC)(link)
Да! Но я постремался усложнять этот пост; тут типа одна тема раскрыта.