[英]HList foldRight is working, but foldLeft does not compile
This is a follow up on my previous question . 这是我以前的问题的跟进。
So, I am trying to compute the (kind-of) powerset of an HList of Options. 因此,我正在尝试计算选项HList的(种类) 功率集。 Basically, I want to interpret the HList as a set, in which case the Option value of an element tells me it belongs to the set or not.
基本上,我想将HList解释为集合,在这种情况下,元素的Option值告诉我它是否属于集合。
I was able to do what I need with the following code: 我可以使用以下代码执行所需的操作:
object combine1 extends Poly2{
implicit def optionA[A,B <: HList] : Case.Aux[Option[A], List[B], List[Option[A] :: B]] = at{(a, hls) =>
val x: List[Option[A] :: B] = hls.flatMap{ hl => a match {
case Some(_) =>
List(
None :: hl,
a :: hl,
)
case None =>
List(None :: hl)
}
}
x
}
implicit def someA[A,B <: HList] : Case.Aux[Some[A], List[B], List[Option[A] :: B]] = at{(a, hls) =>
val x: List[Option[A] :: B] = hls.flatMap{ hl =>
List(
None :: hl,
a :: hl
)
}
x
}
implicit val none : Case.Aux[None.type, List[HList], List[HList]] = at{(_, hls) =>
hls.map(hl => None :: hl)
}
}
All this works fine with foldRight
: 所有这些都可以通过
foldRight
正常工作:
val h1 = Some(2) :: none[BigDecimal] :: Some("b") :: HNil
h1.foldRight(List(HNil))(combine1).foreach(println)
Prints: 印刷品:
// None :: None :: None :: HNil
// Some(2) :: None :: None :: HNil
// None :: None :: Some(b) :: HNil
// Some(2) :: None :: Some(b) :: HNil
However, foldLeft
does not work . 但是,
foldLeft
不起作用 。 Why is that? 这是为什么?
h1.foldLeft(List(HNil))(combine1).foreach(println)
Results in the following: 结果如下:
Error:(72, 26) could not find implicit value for parameter folder: shapeless.ops.hlist.LeftFolder[Some[Int] :: Some[Unit] :: Some[String] :: shapeless.HNil,List[shapeless.HNil.type],swaps.tec.util.Experiment.combine1.type]
What am I missing? 我想念什么?
NB I know that to use foldLeft
I will eventually need to reverse each HList
to get the same results as for foldRight
, but right now I am only interested in actually left-folding the initial HList
. 注:我知道,使用
foldLeft
我最终需要恢复每HList
得到同样的结果作为foldRight
,但现在我只关心实际左折叠初始HList
。 I will fix the out output once I get one :) 一旦得到输出,我将修复输出:)
FoldLeft takes arguments in a different order. FoldLeft以不同的顺序接受参数。 You should define
Case.Aux[List[B], Option[A], ...]
. 您应该定义
Case.Aux[List[B], Option[A], ...]
。
https://en.wikipedia.org/wiki/Fold_(higher-order_function) https://zh.wikipedia.org/wiki/Fold_(高级功能)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.