list – Scala函数中的异构参数
发布时间:2020-12-16 09:27:32 所属栏目:安全 来源:网络整理
导读:如何将一些HList作为参数传递?所以我可以这样做: def HFunc[F,S,T](hlist: F :: S :: T :: HNil) { // here is some code}HFunc(HList(1,true,"String")) // it works perfect 但是,如果我有一个很长的清单,我不知道它,我怎么能对它做一些操作? 我如何通
如何将一些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 } 例如,如果你想要反转你的Hlist并映射结果,你应该像这样使用Mapper和Reverse: 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,"String")) //String :: Boolean :: Int :: HNil = not String :: false :: -1 :: HNil (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |