映射无形记录

时间:2014-10-15 06:30:42

标签: scala record shapeless

在我正在研究的Play应用程序中,我正在尝试改进我们的系统来处理标志,其中一些是用户通过链接导航我们的应用程序时的持久选项。我想使用Shapeless从选项的定义映射到其值,并且还仅从标记为要传播的参数合成新的查询参数。我还希望能够利用Shapeless的Record功能来获得参数值的强类型解除引用。不幸的是,我不确定我是否在Shapeless中以有效的方式接近它。

以下是一段代码,被一些解释性注释所打断。

以下是我正在使用的基本数据类型:

import shapeless._
import poly._
import syntax.singleton._
import record._

type QueryParams = Map[String, Seq[String]]

trait RequestParam[T] {
  def value: T

  /** Convert value back to a query parameter representation */
  def toQueryParams: Seq[(String, String)]

  /** Mark this parameter for auto-propagation in new URLs */
  def propagate: Boolean

  protected def queryStringPresent(qs: String, allParams: QueryParams): Boolean = allParams.get(qs).nonEmpty
}

type RequestParamBuilder[T] = QueryParams => RequestParam[T]

def booleanRequestParam(paramName: String, willPropagate: Boolean): RequestParamBuilder[Boolean] = { params =>
  new RequestParam[Boolean] {
    def propagate: Boolean = willPropagate
    def value: Boolean = queryStringPresent(paramName, params)
    def toQueryParams: Seq[(String, String)] = Seq(paramName -> "true").filter(_ => value)
  }
}

def stringRequestParam(paramName: String, willPropagate: Boolean): RequestParamBuilder[Option[String]] = { params =>
  new RequestParam[Option[String]] {
    def propagate: Boolean = willPropagate
    def value: Option[String] = params.get(paramName).flatMap(_.headOption)
    def toQueryParams: Seq[(String, String)] = value.map(paramName -> _).toSeq
  }
}

实际上,以下是一个类构造函数,它将查询字符串中的Map读取作为参数,但为了简单起见,我只是定义了val

val requestParams = Map("no_ads" -> Seq("true"), "edition" -> Seq("us"))

// In reality, there are many more possible parameters, but this is simplified
val options = ('adsDebug ->> booleanRequestParam("ads_debug", true)) ::
  ('hideAds ->> booleanRequestParam("no_ads", true)) ::
  ('edition ->> stringRequestParam("edition", false)) ::
  HNil

object bind extends (RequestParamBuilder ~> RequestParam) {
  override def apply[T](f: RequestParamBuilder[T]): RequestParam[T] = f(requestParams)
}

// Create queryable option values record by binding the request parameters
val boundOptions = options.map(bind)

这最后一个语句不起作用,并返回错误:

<console>:79: error: could not find implicit value for parameter mapper: shapeless.ops.hlist.Mapper[bind.type,shapeless.::[RequestParamBuilder[Boolean] with shapeless.record.KeyTag[Symbol with shapeless.tag.Tagged[String("adsDebug")],RequestParamBuilder[Boolean]],shapeless.::[RequestParamBuilder[Boolean] with shapeless.record.KeyTag[Symbol with shapeless.tag.Tagged[String("hideAds")],RequestParamBuilder[Boolean]],shapeless.::[RequestParamBuilder[Option[String]] with shapeless.record.KeyTag[Symbol with shapeless.tag.Tagged[String("edition")],RequestParamBuilder[Option[String]]],shapeless.HNil]]]]
           val boundOptions = options.map(bind)

但假设有效,我想做以下事情:

object propagateFilter extends (RequestParam ~> Const[Boolean]) {
  override def apply[T](r: RequestParam[T]): Boolean = r.propagate
}   

object unbind extends (RequestParam ~> Const[Seq[(String, String)]]) {
  override def apply[T](r: RequestParam[T]): Seq[(String, String)] = r.toQueryParams
}

// Reserialize a query string for options that should be propagated
val propagatedParams = boundOptions.values.filter(propagateFilter).map(unbind).toList 
// (followed by conventional collections methods)

我不知道我需要做什么才能让第一个.map调用工作,我怀疑我将遇到下两个多态函数的问题。

1 个答案:

答案 0 :(得分:7)

更新:FieldPoly助手实际上并没有为你做这么多工作,如果没有它,你可以完成同样的事情(并且没有隐含Witness):

import shapeless.labelled.{ FieldType, field }

object bind extends Poly1 {
  implicit def rpb[T, K]: Case.Aux[
    FieldType[K, RequestParamBuilder[T]],
    FieldType[K, RequestParam[T]]
  ] = at[FieldType[K, RequestParamBuilder[T]]](b => field[K](b(requestParams)))
}

值得注意的是,如果你不介意生活危险,你可以跳过返回类型(在两种实现中):

object bind extends Poly1 {
  implicit def rpb[T, K] = at[FieldType[K, RequestParamBuilder[T]]](b =>
    field[K](b(requestParams))
  )
}

但一般来说,使用带有推断返回类型的隐式方法是个坏主意。


正如我在上面的评论中提到的,Case不是协变的,这意味着只有bind的元素被静态输入为{HList时才会有效RequestParamBuilder {1}}(在这种情况下,您没有记录)。

您可以使用.values从记录中获取值,然后您可以映射结果,但是(如您所知)这意味着您丢失了密钥。如果你想保留密钥,你可以使用Shapeless的FieldPoly,它旨在帮助解决这种情况:

import shapeless.labelled.FieldPoly

object bind extends FieldPoly {
  implicit def rpb[T, K](implicit witness: Witness.Aux[K]): Case.Aux[
    FieldType[K, RequestParamBuilder[T]],
    FieldType[K, RequestParam[T]]
  ] = atField(witness)(_(requestParams))
}

现在options.map(bind)将按预期工作。

我认为目前没有更好的方式来写这篇文章,但我并没有非常密切地关注最近的无形发展。在任何情况下,这都是相当清楚的,而不是太冗长,它可以做你想要的。

要回答评论中的其他问题:this previous question是一个起点,但我并未意识到在Shapeless中实现多态函数值的机制非常好。对于博客文章来说,这是一个好主意。