本文介绍了无形:试图通过其类型限制HList元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题1-基本LUBConstraints

我第一次尝试使用现有的LUBConstraints时由于缺少证据而失败(请参见下面的代码块)。有什么提示吗?空列表不是有效的多头列表吗?没有元素违反约束。

My first try playing around with existing LUBConstraints fails for missing evidence (see code block below). Any hint why? Isn't an empty list a valid list of longs? no element violates the constraint.

import shapeless.ops.coproduct
import shapeless.{::, :+:, Coproduct, HNil, HList}

object testLUBConstraints {
  import shapeless.LUBConstraint._

  // !!! see comment on question - this satisfies the implicit below!!! 
  // implicit val hnilLUBForLong = new LUBConstraint[HNil.type, Long] {}

  def acceptLong[L <: HList : <<:[Long]#λ](l: L) = true
  val validLong = acceptLong(1l :: HNil)

  val validEmpty = acceptLong(HNil)
  //  => WHY??? Error: could not find implicit value for evidence parameter of type shapeless.LUBConstraint[shapeless.HNil.type,Long]
  //  MY EXPECTATION WAS: 'implicit def hnilLUB[T] = new LUBConstraint[HNil, T] {}' defined within LUBConstraint companion should provide so

  // val invalid = acceptLong(1.0d :: HNil) -> fails due to missing evidence (as expected)
}

任何帮助表示感谢。

问题2-使用副产品的自身约束
(分为单独的问题:)

问题3-按参数类型限制案例类
(拆分为一个单独的问题:)

推荐答案

HNil 的推断类型将为单例类型 HNil.type ,它是 HNil 的适当子类型。因为像 LUBConstraint 这样的类型类是不变的,所以如果您要查询的话,将找不到 HNil 的任何可用实例。 HNil.type 的实例。

The inferred type of the value HNil will be the singleton type HNil.type, which is a proper subtype of HNil. Because type classes like LUBConstraint are invariant, any available instance for HNil won't be found if you're asking for an instance for HNil.type.

有更改了 HNil 的定义,以使其可行,但这并不简单,尚不清楚该更改的所有含义是否可取。同时,您可以编写 HNil:HNil 来修改值。

There's been some discussion of changing the definition of HNil so that this would work, but it's not trivial, and it's not clear that all the implications of the change are desirable. In the meantime you can write HNil: HNil to upcast the value.

这篇关于无形:试图通过其类型限制HList元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-25 07:24