Scala高阶函数问题

时间:2015-10-22 06:38:34

标签: scala functional-programming

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

有一些功能,如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) = {...}

我可以为process创建一个常见f1, f2功能吗?

有什么想法吗?

感谢。

2 个答案:

答案 0 :(得分: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)

答案 1 :(得分:0)

感谢您的回答,但对我来说不太清楚,请澄清

例如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函数