gpt4 book ai didi

scala - 无形的副产品子类型

转载 作者:行者123 更新时间:2023-12-04 14:22:01 24 4
gpt4 key购买 nike

我试图在 Scala 2.13 中至少模拟联合类型的某些方面。

到目前为止,满足我需求的最佳方法是 coproduct从无形。唯一的问题是子类型没有按我预期的那样工作。下面是一个例子:

import shapeless._

type ISB = Int :+: String :+: Boolean :+: CNil

type ISBSub = Int :+: String :+: CNil

implicitly[ISBSub <:< ISB] // error here

我正在尝试创建一个参数类型为 ISB 的方法并想要这个 def接受 ISBSub以及。
def test(t: ISB) = ???

test(Coproduct[ISBSub](2)) // not working

有什么办法可以用 coproduct 实现这样的目标吗? ?

最佳答案

鉴于 Shapeless 对副产品的编码,这种子集关系不可能与子类型相同。相反,有一个类型类可以证明一个联积是另一个联积的子联合:

scala> import shapeless._
import shapeless._

scala> type ISB = Int :+: String :+: Boolean :+: CNil
defined type alias ISB

scala> type ISBSub = Int :+: String :+: CNil
defined type alias ISBSub

scala> shapeless.ops.coproduct.Basis[ISB, ISBSub]
res0: shapeless.ops.coproduct.Basis[Int :+: String :+: Boolean :+: shapeless.CNil,Int :+: String :+: shapeless.CNil]{type Rest = Boolean :+: shapeless.CNil} = shapeless.ops.coproduct$Basis$$anon$64@ddd69d2

此类型类还允许您在任一方向转换任一联积类型的值:
import shapeless.ops.coproduct.Basis

def shrink[A <: Coproduct, B <: Coproduct](a: A)(implicit ev: Basis[A, B]): Option[B] =
ev(a).toOption

def enlarge[A <: Coproduct, B <: Coproduct](b: B)(implicit ev: Basis[A, B]): A =
ev.inverse(Right(b))

进而:
scala> shrink[ISB, ISBSub](Coproduct[ISB](1))
res0: Option[ISBSub] = Some(Inl(1))

scala> enlarge[ISB, ISBSub](Coproduct[ISBSub](1))
res1: ISB = Inl(1)

一般来说,浏览 shapeless.ops 的内容是值得的。包以了解副产品等支持哪些类型的操作。

关于scala - 无形的副产品子类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58041305/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com