Scala functional programming gymnastics

后端 未结 13 840
悲&欢浪女
悲&欢浪女 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条回答
  •  無奈伤痛
    2021-02-01 10:17

    This isn't really much easier in Scalaz than in regular Scala:

    def restrict(floor: Option[Double], cap: Option[Double], amt: Double) =
      floor.map(amt max).orElse(Some(amt)).map(x => cap.map(x min).getOrElse(x)).get
    

    (Add _ after max and min if it makes you feel better to see where the parameter goes.)

    Scalaz is a little easier to read, though, once you understand what the operators do.

提交回复
热议问题