2012年12月21日金曜日

Konst

この記事はScalaz Advent Calendarの20日目の記事です。

ScalaにはFunction.constという常に一定の値を返す関数があります。

val one = Function.const(1)_
one(2) assert_=== 1
one("hoge") assert_=== 1
view raw const.scala hosted with ❤ by GitHub

この関数を型レベルで表したものがScalazにKonstとして定義されています。

Konst


NaturalTransformationを例にKonstを使ってみます。

new (List ~> Option) {
def apply[A](list: List[A]) = list.headOption
}
new (List ~> Konst[Int]#Apply) {
def apply[A](list: List[A]) = list.size
}
new (Konst[String]#Apply ~> Konst[Int]#Apply) {
def apply[A](string: String) = string.size
}
view raw konst.scala hosted with ❤ by GitHub

あまり使わなさそうですね!
私としてはまだScalaz6にあったPartialApplyの方が便利な気がするのですが。
まあ、型推論がうまくいかなかったり、Unapplyが新しく入ったりしたことが原因にあるのでしょうね。

0 件のコメント:

コメントを投稿