【问题标题】:Providing additional arguments to map on HList提供附加参数以映射到 HList
【发布时间】:2013-05-23 21:59:00
【问题描述】:

我想做这样的事情:

def run(subjects: List[Subject]) = {
  val configs = compute()
  subjects.map(s => configs.map(c => test(s,c)))
  // or flatMap, I don't really care at this point
}

在我的用例中,主题实际上是Subject[T],我需要在结果中使用T 的类型安全版本。所以我有:

def run[L <: HList](subjects: L)(implicit mapper: Mapper[testFun.type, L]) = {
  val configs = compute()
  subjects.map(testFun)
}

但是,现在我无法将配置传递给testFun,根据this post,它需要有一个单例类型。

一种选择是:

val cfgHL = HList.fill(subjects.length)(configs)
(subjects zip cfgHL).map(testFun)

HList 目前没有fill 操作。有什么提示吗?

【问题讨论】:

  • HList 现在有一个填充方法(虽然还没有正式发布)。

标签: scala shapeless


【解决方案1】:

您可以使用mapConst 完成与fill 相同的事情。如果我们有以下情况:

val xs = 1 :: 'a :: 'a' :: HNil

我们可以这样写:

scala> xs.zip(xs mapConst "x") == (1, "x") :: ('a, "x") :: ('a', "x") :: HNil
res0: Boolean = true

请注意,还有其他方法可以解决部分应用(更高等级)多态函数然后与它们进行映射的问题 - 例如参见 my answer here。不过,对于您的用例来说,这样的事情可能有点过头了。

【讨论】:

    猜你喜欢
    • 2019-06-24
    • 2015-12-03
    • 2012-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-26
    相关资源
    最近更新 更多