CLOVER🍀

That was when it all began.

Scalaz IntW

APIを見てみたら、意外と数が少なかったので勢いでそのままIntWもやってみました。

ordering

実行すると、Orderingトレイトのサブクラス、EQ、GT、LTが返ってきます。それぞれ、0、正の数、負の数にマッピングされている模様。

  println("-10 ordering => " + {
    -10 ordering
  })
  println("0 ordering => " + {
    0 ordering
  })
  println("10 ordering => " + {
    10 ordering
  })

実行結果。

-10 ordering => LT
0 ordering => EQ
10 ordering => GT

これは、後でもうちょっと書きます。

times

掛け算をするっぽいです。

  println("10 times 3 => " + {
    10 times 3
  })
  println("10 times -10 => " + {
    10 times -10
  })
  println("-10 times 3 => " + {
    -10 times 3
  })
  println("-10 times -10 => " + {
    -10 times -10
  })
  println("0 times 10 => " + {
    0 times 10
  })

実行結果。

10 times 3 => 30
10 times -10 => -100
-10 times 3 => 0
-10 times -10 => 0
0 times 10 => 0

負の数または0に対してtimesメソッドを使用しても、結果は0になります。コードを見た感じだと、m times nの時m X nではなくて、n X mで考えているみたいですね。んで、mを1ずつ引きながらmが正の間だけ繰り返していくので負の数または0を基点に始めると、結果が0になるようです。

たぶんこれは、単体では効果を発揮しません。前はこれをfoldMapで使用していましたが、こういう畳み込みの時に演算を指示するためのもの、ということでよいのかな?意味的にはおそらく掛け算。

  println("10 ∏ => " + {
    10 ∏
  })
  println("100 ∏ => " + {
    100 ∏
  })

実行結果。

10 ∏ => 10
100 ∏ => 100

この中ではorderingがよくわからなかったので、コードをちょっと見てみました。

scalaz.IntW#ordering

  def ordering: Ordering = if (value < 0) LT else if (value > 0) GT else EQ

scalaz.Ordering

package scalaz

sealed trait Ordering {
  val toInt: Int
}
case object LT extends Ordering {
  val toInt = -1
}
case object EQ extends Ordering {
  val toInt = 0
}
case object GT extends Ordering {
  val toInt = 1
}

中身はtoIntメソッドだけで、-1と0と1しか意識してませんね。もしかして、compareToあたりで使うのかな?

  print("1 comopareTo 10 ordering => ")
  (1 compareTo 10 ordering) match {
    case EQ => println("等しい")
    case GT => println("大きい")
    case LT => println("小さい")
  }
1 comopareTo 10 ordering => 小さい

こういう使い方でいいのでしょうか…?