LoginSignup
7
9

More than 5 years have passed since last update.

Scalazの"~>"ってなに?(Scalaの中置記法について)

Posted at

ScalazのFreeモナドについて勉強中なのですが、ryobbyさんのscalaz - Freeの記事を拝見している際に

val interpMock = new (Command ~> Id) {
  def apply[A](a: Command[A]): A = a match {
    ...
  }
}

という構文が出てきまして、本題のFreeモナド以前に「この"~>"ってなんだ?(-_-;)」っていうところで躓いてしまったので、調べてみました。

~>の定義

pakage.scala
package object scalaz {
  type ~>[-F[_], +G[_]] = NaturalTransformation[F, G]
}
NaturalTransformation.scala
trait NaturalTransformation[-F[_], +G[_]] {
  ...
}

要するに~>[A, B]NaturalTransformation[A, B]のエイリアスのようです。

しかし問題のコードは

val interpMock = new ~>[Command, Id] {

ではなく

val interpMock = new (Command ~> Id) {

という記述になっています。なぜこんな記法が可能なのでしょうか?

中置記法

kmizuさんのScala変態技法最速マスターに答えが書いてありました。引用させて頂きますと

Scalaでは2つの型パラメータを持つジェネリックな型は中置記法で書くことができるというシンタックスシュガーが導入されています。

とのことです。

ということで、typeによるエイリアス指定と合わせて、

val interpMock = new (Command ~> Id) {
  ...
}

val interpMock = new NaturalTransformation[Command, Id] {
  ...
}

だということですね。

実験

一応自分でコードを書いて実験してみました。

class MySample[F, G]
// defined class MySample

type ~>[F, G] = MySample[F, G]
// defined type alias $tilde$greater

new ~>[Int, String]
// MySample[Int,String] = MySample@158d255c

new (Int ~> String) // こう書ける
// MySample[Int,String] = MySample@48e64352

new (Int MySample String) // これもオーケー(恐ろしい)
// MySample[Int,String] = MySample@51a06cbe

new Int ~> String // これは駄目
// error: object java.lang.String is not a value

まとめ

GoogleでScalaの記号を検索する場合の用語集が欲しいですね・・・(-_-;)。

("~>"の場合は"scala tilde greater"で検索すると色々ヒットしました)

7
9
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
9