This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
object mapBetween { | |
implicit def seqToExtSeq[A](seq: Seq[A]) = new { | |
def mapBetween[B](f: (A, A) => B): Iterator[B] = { | |
seq.sliding(2).map(s => f(s(0), s(1))) | |
} | |
} | |
def main(args: Array[String]) { | |
val range2 = 1 to 10 | |
println(range2.mapBetween(_ + _) mkString ",") | |
println(range2.mapBetween(_ * _) mkString ",") | |
println(range2.mapBetween(_ - _) mkString ",") | |
} | |
} |
traitとして別途宣言せず、mapBetween関数が追加された無名クラスのインスタンスを返すようにimplicit conversionを定義する。(3〜7行目)
Seqのサブクラスとして何が来ようと、そのクラスを拡張した形で無名クラスが定義されるため、返り値がmutableになってしまうこともない。何より大変シンプルになってわかりやすい。
今度のseqToExtSeq関数の返り値は無名クラスのインスタンスになるため、返り値の型を明示できない。そのためか、main関数の後に定義すると、以下のようなエラーが出てコンパイル出来なかった。
value mapBetween is not a member of scala.collection.immutable.Range.Inclusive Note: implicit method seqToExtSeq is not applicable here because it comes after the application point and it lacks an explicit result type mapBetween.scala
順番が入れ替わっているのはそのため。
とりあえず最初の手習いとしてはこれくらいにして、次は別のことをやってみる。
とりあえず最初の手習いとしてはこれくらいにして、次は別のことをやってみる。