【问题标题】:Heterogeneous arguments in a Scala functionScala 函数中的异构参数
【发布时间】:2013-11-07 04:50:17
【问题描述】:

我怎样才能传递一些HList 作为参数?所以我可以这样制作:

def HFunc[F, S, T](hlist: F :: S :: T :: HNil) {
    // here is some code
}

HFunc(HList(1, true, "String")) // it works perfect

但是,如果我有一个很长的列表,而我对此一无所知,我该如何对其进行一些操作呢? 如何传递参数而不丢失其类型?

【问题讨论】:

  • 你想在方法体中执行什么样的操作?
  • hm,一些类型相关的对象可以存储在这个列表中,我不想丢失有关对象类型的信息。所以我需要对HLists - map, head, etc... 进行mb所有操作:)

标签: list scala shapeless heterogeneous hlist


【解决方案1】:

这取决于您的用例。

HList 对类型级代码很有用,因此您不仅应该将HList 传递给您的方法,还应该传递所有必要的信息,如下所示:

def hFunc[L <: HList](hlist: L)(implicit h1: Helper1[L], h2: Helper2[L]) {
    // here is some code
}

例如,如果你想reverse 你的Hlistmap 超过结果,你应该像这样使用MapperReverse

import shapeless._, shapeless.ops.hlist.{Reverse, Mapper}

object negate extends Poly1 {
  implicit def caseInt = at[Int]{i => -i}
  implicit def caseBool = at[Boolean]{b => !b}
  implicit def caseString = at[String]{s => "not " + s}
}

def hFunc[L <: HList, Rev <: HList](hlist: L)(
                              implicit rev: Reverse[L]{ type Out = Rev },
                                       map: Mapper[negate.type, Rev]): map.Out =
  map(rev(hlist)) // or hlist.reverse.map(negate)

用法:

hFunc(HList(1, true, "String"))
//String :: Boolean :: Int :: HNil = not String :: false :: -1 :: HNil

【讨论】:

  • y,我看到了,例如:def hFunc[L &lt;: HList](hlist: L)(implicit m: TypeTag[L])m 中有关于对象类型的所有信息;但我不能制作hlist.head,因为事实上hlist 参数有另一种类型;它抛出一个错误(在制作hlist.head):could not find implicit value for parameter c: shapeless.IsHCons[L]
  • @DaunnC:不是TypeTag。你应该使用Mapper 代表mapReverse 代表reverse 等等。
  • @DaunnC:我猜shapeless 源、示例和测试是最好的学习资源。您还可以阅读 stackoverflow questions。我不知道其他有用的链接。请参阅我的答案中的更新以获取代码示例。
猜你喜欢
  • 2013-09-08
  • 2013-03-16
  • 2016-02-19
  • 1970-01-01
  • 1970-01-01
  • 2013-05-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多