Comment detail

法演算 (Nested Flatten)

shiroさんと同じく言語のイディオムっちゅーことで、Scalaではこんな風にDSLっぽくしたりしますよ、という例をかねて。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
class WithModulo(m:int){
  class MInt(self: int){
    def +(i:int) = eval(i, '+')
    def -(i:int) = eval(i, '-')
    def *(i:int) = eval(i, '*')
    def norm(i:int) = {
      if(i<0) (m*(i.abs/m+1))+i
      else i%m
    }

    def eval(i:int, op:char ) = {
      print(self + " " + op + " " + i + " = ")
      if(!List(self, i).forall{i => i >=0 && i < m}) {
        print(norm(self)+ " " + op + " " + norm(i) + " = ")
      }
      println(op match {
        case '+' => norm(self+i)
        case '-' => norm(self-i)
        case '*' => norm(self*i)
        case _  => 0
      })
    }
  }
  def ~(i: int) = new MInt(i)
}
def withModulo(m:int) = new WithModulo(m)


withModulo(10) ~ 3 - 2
withModulo(10) ~ 1 + 2
withModulo(10) ~ 18 * 39

Index

Feed

Other

Link

Pathtraq

loading...