Scala functional programming gymnastics

后端 未结 13 679
悲&欢浪女
悲&欢浪女 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

    I'm adding another answer which was inspired by both retronym and Debilski - basically it amounts to converting the cap and floor to functions (Double => Double, if they are present) and then folding the identity function through them with composition:

    def restrict(floor: Option[Double], cap: Option[Double], amt: Double) = {
      (identity[Double] _ /: List(floor.map(f => (_: Double) max f), cap.map(c => (_: Double) min c)).flatten){ _ andThen _ }(amt)
    }
    

提交回复
热议问题