代码之家  ›  专栏  ›  技术社区  ›  DaunnC

Scala函数中的异构参数

  •  7
  • DaunnC  · 技术社区  · 11 年前

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

    def HFunc[F, S, T](hlist: F :: S :: T :: HNil) {
        // here is some code
    }
    
    HFunc(HList(1, true, "String")) // it works perfect
    

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

    1 回复  |  直到 11 年前
        1
  •  8
  •   senia    11 年前

    这取决于您的用例。

    HList 对于类型级代码是有用的,因此您不仅应该传递给您的方法 HList公司 ,还有所有必要的信息,如:

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

    例如,如果你想 reverse 你的 Hlist map 超出您应该使用的结果 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, true, "String"))
    //String :: Boolean :: Int :: HNil = not String :: false :: -1 :: HNil