list - Scala 函数中的异构参数

标签 list scala shapeless heterogeneous hlist

我怎样才能通过一些 HList作为论据?所以我可以这样制作:

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

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

但是如果我有一个很长的列表,我什么都不知道,我如何对其进行一些操作?
如何传递参数而不是丢失其类型?

最佳答案

这取决于您的用例。
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

关于list - Scala 函数中的异构参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19634394/

相关文章:

python - 元组构造函数与列表组合

python - 将 Spark DataFrame 从 Python 迁移到 Scala whithn Zeppelin

scala - 如何使用shapeless检测字段类型注释

scala - 在需要函数的地方使用构造函数

scala - 在 shapeless 中,有两个列表,其中一个包含另一个的类型类

scala - 为无形 hlist 定义 scalaz monad 实例

python - 在 Pandas Dataframe 中展平列表的更快方法

python - 列表查找比元组更快?

java - 按相反顺序对列表进行排序并删除重复项

scala - 如何在 Scala for 循环中指定一个 'next' 函数