gpt4 book ai didi

scala - 约束左右类型签名

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

给定以下 AST SuccessFailure :

sealed trait Success
case object FooGood extends Success
case object BarGood extends Success

sealed trait Failure
case object FooBad extends Failure
case object BarBad extends Failure

和方法签名:
def go[A <: Failure, B <: Success](x: Int): Either[A, B] = ???

但是,我想限制 LeftRight特定于 Foo 的类型或 Bar .

但是下面的代码编译(违背我的意愿):
scala> go[FooBad.type, BarGood.type](5)
scala.NotImplementedError: an implementation is missing

如何在编译时实现此约束?

最佳答案

这是一个依赖于类型类的解决方案。值得注意的是,它不需要为每个(对)AST 节点手动定义新的类型类实例。
它确实涉及为每一对引入一个通用的父类(super class)型(尽管技术上您没有 将其用作基类,但它仅用作标记类型)。

sealed trait Success[T]
abstract sealed class Foo
abstract sealed class Bar
case object FooGood extends Foo with Success[Foo]
case object BarGood extends Bar with Success[Bar]
sealed trait Failure[T]
case object FooBad extends Foo with Failure[Foo]
case object BarBad extends Bar with Failure[Bar]

@annotation.implicitNotFound("Expecting reciprocal Failure and Success alternatives, but got ${A} and ${B}")
trait IsGoodAndBadFacet[A,B]
implicit def isGoodAndBadFacet[T,A,B](implicit e1: A <:< Failure[T], e2: B<:<Success[T]): IsGoodAndBadFacet[A,B] = null

def go[A, B](x: Int)(implicit e: IsGoodAndBadFacet[A,B]): Either[A, B] = ???

复试:
scala> go[FooBad.type, BarGood.type](5)
<console>:17: error: Expecting reciprocal Failure and Success alternatives, but got FooBad.type and BarGood.type
go[FooBad.type, BarGood.type](5)
^

scala> go[FooBad.type, FooGood.type](5)
scala.NotImplementedError: an implementation is missing
at scala.Predef$.$qmark$qmark$qmark(Predef.scala:225)
at .go(<console>:11)
... 33 elided

scala> go[BarBad.type, BarGood.type](5)
scala.NotImplementedError: an implementation is missing
at scala.Predef$.$qmark$qmark$qmark(Predef.scala:225)
at .go(<console>:11)
... 33 elided

关于scala - 约束左右类型签名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32610905/

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