【问题标题】:Scala higher order function issueScala高阶函数问题
【发布时间】:2015-10-22 06:38:33
【问题描述】:

我的目标:尽量减少代码行数。

有一些功能,如f1f2 ...

f1(A: String)

f2(A: String, B: Long, C: User)

想用高阶函数方法处理它。

def processf1(request: Request[AnyContent], f: (String) => String)

def processf2(request: Request[AnyContent], f: (String, Long, User) => String) = {...}

我可以为f1, f2 创建ONE 通用process 函数吗?

有什么想法吗?

谢谢。

【问题讨论】:

    标签: scala functional-programming


    【解决方案1】:

    您可以参数化processf 类型:

    def processf[S,T](request: Request[S], f: T => String) = ...
    

    使用示例:

    processf(new Request[Int], (x: String) => x)
    
    processf(new Request[Int], (x: (String, Long, User)) => x._1)
    

    【讨论】:

      【解决方案2】:

      谢谢你的回答,但对我来说不是很清楚,请澄清一下

      例如 3 个重复的函数,如 RequestUtil.getRequestParams

        private def regUser(request: Request[AnyContent], f: (String) => String): String = {
          RequestUtil.getRequestParams(request, APPConst.USER) match {
            case Some(map) => f(map(APPConst.USER))
            case None => JsonUtil.toJson(APPConst.ERROR -> APPConst.POST_PARAMS_EMPTY_MISMATCH)
          }
        }
      
        private def regDog(request: Request[AnyContent], f: (Dog, Enum, String, String) => String): String = {
          RequestUtil.getRequestParams(request, APPConst.Dog) match {
            case Some(m) => process(m, f)
            case None => JsonUtil.toJson(APPConst.ERROR -> APPConst.POST_PARAMS_EMPTY_MISMATCH)
          }
        }
      
        private def regCat[T](request: Request[AnyContent], f: (Cat, Enum) => String): String = {
          RequestUtil.getRequestParams(request, APPConst.CAT) match {
            case Some(map) => process(map, f)
            case None => JsonUtil.toJson(APPConst.ERROR -> APPConst.POST_PARAMS_EMPTY_MISMATCH)
          }
        }
      

      和处决

       def regUser = Action { request => Ok(views.html.index(regUserProcess(request, UserService.regUser)))}
      
        def regDog = Action { request => Ok(views.html.index(regCurrProcess(request, UserService.regDog)))}
      
        def regCat = Action { request => Ok(views.html.index(mainProcess(request, UserService.regCat)))}
      

      如您所见,3 个不同的函数具有不同的计数参数UserService.regUser, UserService.regDog, UserService.regCat 函数

      【讨论】:

      • 在 Scala 中,您可以按类型对函数进行参数化。例如:f(x: Int): String = x.toStringg(x: Int): x.toString 可以表示为唯一函数 f[T](x: T): = x.toString。由于 Scala 的类型推断,您可以将f 称为f(1)f("1")。我的回答适用相同的策略,但适用于您传递类型的函数。
      • 对于您的方法,它们可以合并为一个类型参数化的单一方法:private def regUser[T, S](request: Request[AnyContent], f: T => String, params: S): String = { params match { case Some(x) => f(x); case None => JsonUtil.toJson(APPConst.ERROR -> APPConst.POST_PARAMS_EMPTY_MISMATCH); } }
      • 顺便说一句,您不应该回答您的问题来添加更多信息。您应该编辑您的原始帖子。
      猜你喜欢
      • 2021-02-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多