Scala functional programming gymnastics

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

    I'll start with this:

    def restrict(floor : Option[Double], cap : Option[Double], amt : Double) : Double = {
      val flooring = floor.map(f => (_: Double) max f).getOrElse(identity[Double] _)       
      val capping  = cap.map(f => (_: Double) min f).getOrElse(identity[Double] _)         
      (flooring andThen capping)(amt)                                                      
    }                                                                                    
    

    But I have the feeling I'm missing some opportunity here, so I may not be finished.

提交回复
热议问题