Scala functional programming gymnastics

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

    I find that when a question asks to use an Option to indicate an optional parameter, there's usually a more natural way to represent the missing parameter. So I'm going to change the interface a little here, and use default arguments to define the function and named parameters to call the function.

    def restrict(amt:Double,
                floor:Double = Double.NegativeInfinity,
                cap:Double=Double.PositiveInfinity):Double =
        (amt min cap) max floor
    

    Then you can call:

    restrict(6)
    restrict(6, floor = 7)
    restrict(6, cap = 5)
    

    (Another example of the same principle.)

提交回复
热议问题