Why no i++ in Scala?

前端 未结 11 1829
半阙折子戏
半阙折子戏 2020-12-23 10:48

I just wonder why there is no i++ to increase a number. As what I know, languages like Ruby or Python doesn\'t support it because they are dynamically typed. So

11条回答
  •  生来不讨喜
    2020-12-23 11:36

    Of course you can have that in Scala, if you really want:

    import scalaz._, Scalaz._
    
    case class IncLens[S,N](lens: Lens[S,N], num: Numeric[N]) { 
      def ++ = lens.mods(num.plus(_, num.one))
    }
    
    implicit def incLens[S,N: Numeric](lens: Lens[S,N]) =
      IncLens[S,N](lens, implicitly[Numeric[N]])
    
    val i = Lens.lensu[Int,Int]((x, y) => y, identity)
    
    val imperativeProgram = for {
      _ <- i++;
      _ <- i++;
      x <- i++
    } yield x
    
    def runProgram = imperativeProgram exec 0
    

    And here you go:

    scala> runProgram
    res26: scalaz.Id.Id[Int] = 3
    

    No need to resort to violence against variables.

提交回复
热议问题