gpt4 book ai didi

scala - 在 Shapeless 记录上映射

转载 作者:行者123 更新时间:2023-12-04 02:17:13 25 4
gpt4 key购买 nike

在我正在开发的 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打电话上类,我怀疑接下来的两个多态函数会遇到问题。

最佳答案

更新:FieldPoly helper 在这里实际上并没有为你做那么多工作,你可以在没有它的情况下完成同样的事情(并且没有 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 (在这种情况下,您没有记录)。

您可以使用 .values从记录中获取值,然后您可以映射结果,但是(正如您所注意到的)这意味着您会丢失 key 。如果要保留 key ,可以使用 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)将按预期工作。

我认为目前没有更好的方法来写这个,但我没有密切关注最近的 Shapeless 发展。在任何情况下,这都是相当清楚的,不是太冗长,它可以满足您的需求。

回答您评论中的另一个问题: this previous question是一个起点,但我不知道在 Shapeless 中实现多态函数值的机制的真正好的概述。这是博客文章的好主意。

关于scala - 在 Shapeless 记录上映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26375886/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com