1

我试试

import shapeless._
val ilist = List(1,2,3) ; 
val slist = List("a", "b", "c") ; 
(ilist :: slist :: HNil).map(list: List[_] => list -> list.length)

并且编译器说它需要映射函数中的参数类型,或者在提供类型时找不到listList[_]。有一个简单的映射示例吗?

普通的 Scala 列表没有这样的问题

    val list1 = 1 :: 2 :: Nil; val list2 = 3 :: 4 :: Nil
    (list1 :: list2 :: Nil) map {list => list -> list.length}

编译得很好。

4

1 回答 1

2

I'm a no shapeless expert, but I'm sure you can do that with ~>>. The thing is that map accepts Poly, so you need a Poly function that returns a constant. This is what ~>> is.

  import shapeless._
  import poly._
  val ilist = List(1,2,3) ;
  val slist = List("a", "b", "c") ;

  object fun extends (List ~>> Int) {
    override def apply[T](f: List[T]): Int = f.size
  }

  println((ilist :: slist :: HNil).map(fun))

Note, that ~>> is actually:

type ~>>[F[_], R] = ~>[F, Const[R]#λ]
于 2016-01-17T11:02:18.997 回答