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] www-dikinet.livejournal.com 2013-01-24 05:00 am (UTC)(link)
Че-то всё не по-русски?

[identity profile] ivan-gandhi.livejournal.com 2013-01-24 05:09 am (UTC)(link)
Я уже лет тридцать как на такие темы предпочитаю рассуждать по-английски. И Вам советую освоить, если Вы хотите программировать профессионально.

я просто удилась, куда пропали русские буквы

[identity profile] www-dikinet.livejournal.com 2013-01-24 05:21 am (UTC)(link)
Image


а потом вдруг появилсь?

Re: я просто удилась, куда пропали русские буквы

[identity profile] ivan-gandhi.livejournal.com 2013-01-24 05:36 am (UTC)(link)
:) Русские буквы не пропадут!

[identity profile] xeno-by.livejournal.com 2013-01-24 06:22 am (UTC)(link)
А какой у флаттена тут возвращаемый тип?

[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)
Да! Но я постремался усложнять этот пост; тут типа одна тема раскрыта.

[identity profile] lomeo.livejournal.com 2013-01-24 07:11 am (UTC)(link)
scala> sealed abstract class <:<[-S, +T] extends Function1[S, T]
defined class $less$colon$less

scala> implicit def canCast[F <% T, T]: (F <:< T) = new (F <:< T) { def apply(a: F): T = a }
canCast: [F, T](implicit evidence$1: F => T)<:<[F,T]

scala> case class L[X](val x: X) { def double[Y](implicit transformer: X <:< Int) = x*2 }
defined class L

scala> L(42).double
res16: Int = 84

scala> L("a").double
<console>:26: error: diverging implicit expansion for type <:<[String,Int]
starting with method canCast
              L("a").double


А вот с
implicit def canCast[F <: T, T]: (F <:< T) = new (F <:< T) { def apply(a: F): T = a }

уже не работает…

P.S. Сорри за множественные правки: сначала больше-меньше побилось в html, затем заметил, что лишний кусок прихватил.
Edited 2013-01-24 07:15 (UTC)

[identity profile] ivan-gandhi.livejournal.com 2013-01-24 07:55 am (UTC)(link)
О, спасибо, конечно <%

[identity profile] sassa-nf.livejournal.com 2013-01-24 10:19 am (UTC)(link)
алсо,

case class L[X](val x: X) { def double[_ >: X <: Int] = /* safe to cast now */ (x.asInstanceOf[Int])*2 } жаль, конечно, что скала не умеет умозаключить, что X - субкласс Int из экзистенциального баунда на _.

[identity profile] xeno-by.livejournal.com 2013-01-24 10:35 am (UTC)(link)
У нас констрейнты на type vars весьма ограниченные + очень локальные (одно из размышлений на эту тему с участием Мартина и Спивака: http://pchiusano.blogspot.ch/2011/05/making-most-of-scalas-extremely-limited.html).

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

Конкретно по деталям реализации, есть символ X, у него есть сигнатура, однозначно определяемая его дефинишеном и никак не изменяемая. Types.isSubType определен в scala-reflect.jar, т.е. он ничего не знает про контексты тайпчекера, определенные в scala-compiler.jar, т.е. единственное, что он может сделать - спросить у символа сигнатуру => фейл.

[identity profile] sassa-nf.livejournal.com 2013-01-24 11:55 am (UTC)(link)
спасибо.

а почему implicit вот такого вида не работает:
implicit def safeCast[X,Y, _ >: X <: Y]( x:X ):Y = x.asInstanceOf[Y]
case class L[X](val x: X) { def double[_ >: X <: Int] = x*2 }
Edited 2013-01-24 11:56 (UTC)

[identity profile] xeno-by.livejournal.com 2013-01-24 12:02 pm (UTC)(link)
Можно, пожалуйста, полный сниппет, который не компилируется? Я, если честно, не понял, куда safeCast должен примениться в твоем примере.
Edited 2013-01-24 12:03 (UTC)

[identity profile] sassa-nf.livejournal.com 2013-01-24 12:23 pm (UTC)(link)
он должен был попасть в x*2, заменяя x.asInstanceOf[Int], который был изначально.

http://ideone.com/bpLenc - не компилируется; говорит, x не Int

http://ideone.com/MlYeRN - всё в порядке, но и каст explicitly

Edited 2013-01-24 12:31 (UTC)

(no subject)

[identity profile] xeno-by.livejournal.com - 2013-01-24 12:34 (UTC) - Expand

(no subject)

[identity profile] xeno-by.livejournal.com - 2013-01-24 12:39 (UTC) - Expand

(no subject)

[identity profile] sassa-nf.livejournal.com - 2013-01-24 12:56 (UTC) - Expand

(no subject)

[identity profile] xeno-by.livejournal.com - 2013-01-24 13:05 (UTC) - Expand

(no subject)

[identity profile] xeno-by.livejournal.com - 2013-01-24 13:07 (UTC) - Expand

(no subject)

[identity profile] sassa-nf.livejournal.com - 2013-01-24 13:19 (UTC) - Expand

(no subject)

[identity profile] sassa-nf.livejournal.com - 2013-01-24 18:11 (UTC) - Expand

[identity profile] lomeo.livejournal.com 2013-01-24 11:33 am (UTC)(link)
А, точно. Так же гораздо проще.

[identity profile] sassa-nf.livejournal.com 2013-01-25 10:57 am (UTC)(link)
     case class L[X](val x:X) {
        def double[P >: X <: Int]: Int = (x:P) * 2
    }
(this scala awesomeness brought to you courtesy of Roland Kuhn)

(всё ещё жаль, что не догадывается, что x is Int, но уже значительно лучше!)

[identity profile] ivan-gandhi.livejournal.com 2013-01-25 07:55 pm (UTC)(link)
Funny, how much effort it took to figure out this specific format.
And it involved great minds, too. :)

[identity profile] sassa-nf.livejournal.com 2013-01-26 11:20 am (UTC)(link)
Great to listen to great minds!

But frustrating that you need to know which way will work (vs which way is correct)

[identity profile] vit-r.livejournal.com 2013-01-24 08:59 am (UTC)(link)
define methods that would only work if X satisfies certain conditions

Что конкретно должно происходить, когда вызывается метод, который не работает? И что сделает реальный программист в таком случае?

[identity profile] sassa-nf.livejournal.com 2013-01-24 09:20 am (UTC)(link)
не компилируется.

e.g. List[String].sum не откомпилируется.

[identity profile] vit-r.livejournal.com 2013-01-24 09:46 am (UTC)(link)
Не компилируется - это значит, компилятор выдаёт ошибку. Вопрос в том, какая она будет для небанального случая и что сделает программист в результате?

Не то, чтобы я не видел подобного в реале, но просто интересны предположения тех, кто такое позволяет.

[identity profile] xeno-by.livejournal.com 2013-01-24 10:41 am (UTC)(link)
Скажет, что не найден имплисит. Такие сообщения можно кастомизировать при помощи аннотации на классе имплисита: https://github.com/scalamacros/kepler/blob/18a906bb9a6c6b50d286ca76f219a5b351514ae4/src/library/scala/collection/generic/CanBuildFrom.scala#L28.

[identity profile] vit-r.livejournal.com 2013-01-24 10:49 am (UTC)(link)
Насколько я понимаю английский, "cannot construct" это немного не то же самое, что "не найден". Так что действия после обнаружения ошибки будут совсем не те, что предполагают жители башни из слоновой кости.

(no subject)

[identity profile] xeno-by.livejournal.com - 2013-01-24 10:58 (UTC) - Expand

(no subject)

[identity profile] vit-r.livejournal.com - 2013-01-24 11:16 (UTC) - Expand

(no subject)

[identity profile] xeno-by.livejournal.com - 2013-01-24 11:25 (UTC) - Expand

(no subject)

[identity profile] vit-r.livejournal.com - 2013-01-24 11:30 (UTC) - Expand

(no subject)

[identity profile] xeno-by.livejournal.com - 2013-01-24 11:33 (UTC) - Expand

(no subject)

[identity profile] vit-r.livejournal.com - 2013-01-24 12:04 (UTC) - Expand

(no subject)

[identity profile] xeno-by.livejournal.com - 2013-01-24 12:30 (UTC) - Expand

(no subject)

[identity profile] vit-r.livejournal.com - 2013-01-24 12:39 (UTC) - Expand

(no subject)

[identity profile] xeno-by.livejournal.com - 2013-01-24 12:45 (UTC) - Expand

(no subject)

[identity profile] sassa-nf.livejournal.com - 2013-01-28 19:06 (UTC) - Expand

(no subject)

[identity profile] ivan-gandhi.livejournal.com - 2013-01-28 19:34 (UTC) - Expand

(no subject)

[identity profile] xeno-by.livejournal.com - 2013-01-28 19:43 (UTC) - Expand

(no subject)

[identity profile] ivan-gandhi.livejournal.com - 2013-01-28 22:01 (UTC) - Expand

(no subject)

[identity profile] xeno-by.livejournal.com - 2013-01-28 22:23 (UTC) - Expand

(no subject)

[identity profile] sassa-nf.livejournal.com - 2013-01-28 20:35 (UTC) - Expand

(no subject)

[identity profile] xeno-by.livejournal.com - 2013-01-24 11:31 (UTC) - Expand

(no subject)

[identity profile] vit-r.livejournal.com - 2013-01-24 12:08 (UTC) - Expand

(no subject)

[identity profile] xeno-by.livejournal.com - 2013-01-24 12:10 (UTC) - Expand

(no subject)

[identity profile] vit-r.livejournal.com - 2013-01-24 12:19 (UTC) - Expand

(no subject)

[identity profile] xeno-by.livejournal.com - 2013-01-24 12:24 (UTC) - Expand

(no subject)

[identity profile] vit-r.livejournal.com - 2013-01-24 12:45 (UTC) - Expand

(no subject)

[identity profile] xeno-by.livejournal.com - 2013-01-24 12:27 (UTC) - Expand

(no subject)

[identity profile] vit-r.livejournal.com - 2013-01-24 12:41 (UTC) - Expand