Scala functional programming gymnastics

后端 未结 13 868
悲&欢浪女
悲&欢浪女 2021-02-01 09:36

I am trying to do the following in as little code as possible and as functionally as possible:

def restrict(floor : Option[Double], cap : Option[Double], amt : D         


        
13条回答
  •  旧时难觅i
    2021-02-01 10:41

    How about this?

    //WRONG
    def restrict(floor : Option[Double], cap : Option[Double], amt : Double) : Double = 
       (floor.getOrElse(amt) max amt) min cap.getOrElse(amt)
    

    [Edit]

    Second try:

    def restrict(floor : Option[Double], cap : Option[Double], amt : Double) : Double = 
       floor.map(f => f max _).getOrElse(identity[Double] _)(
         cap.map(c => c min _).getOrElse(identity[Double] _)(amt))
    

    Looks a little bit too "lispy" for my taste, but passes the tests :-)

    [2nd Edit]

    The first version can be "repaired", too:

    def restrict(floor: Option[Double], cap: Option[Double], amt: Double): Double =
      (floor.getOrElse(-Double.MaxValue) max amt) min cap.getOrElse(Double.MaxValue)
    

提交回复
热议问题