标量中scala中的联合类型:A | B <:A | B | C [英] union types in scala with subtyping: A|B &lt;: A|B|C

查看:266
本文介绍了标量中scala中的联合类型:A | B <:A | B | C的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将A|B类型作为A|B|C的子类型.可以在Scala中编码吗?如果是,怎么办?

I would like to have a A|B type to be the subtype of A|B|C. Is that possible to encode in Scala ? If yes, how ?

我希望可以在下面进行implicitly[¬¬[IF] <:< T]编译(原始代码

I was hoping that I can make implicitly[¬¬[IF] <:< T] compile below (original code here), but it does not. Is there a way to fix this code to allow subtyping ?

object NUnion{
  type ¬¬[A] = ¬[¬[A]]

  type ¬[A] = A => Nothing
  trait Disj[T] {
    type or[S] = Disj[T with ¬[S]]
    type apply = ¬[T]
  }

  // for convenience
  type disj[T] = { type or[S] = Disj[¬[T]]#or[S] }


  type T = disj[Int]#or[Float]#or[String]#apply
  type IF = disj[Int]#or[Float]#apply
  implicitly[¬¬[Int] <:< T] // works
  // implicitly[¬¬[Double] <:< T] // doesn't work
  // implicitly[¬¬[IF] <:< T] // doesn't work - but it should

}

我也尝试过此操作(来自此处):

I also tried this (from here):

object Kerr{
  def f[A](a: A)(implicit ev: (Int with String with Boolean) <:< A) = a match {
     case i: Int => i + 1
     case s: String => s.length
  }

  f(1) //works
  f("bla") // works
  def g[R]()(implicit ev: (Int with String with Boolean) <:< R):R = "go" // does not work

}

但是在这里,我不能将联合类型设为一流",它们只能作为参数类型存在,而不能作为返回类型存在.

but here I cannot make a union type "first-class" they can only exist as argument types, not as return types.

方法存在相同的问题:

Same problem with this approach :

object Map{
  object Union {
    import scala.language.higherKinds

    sealed trait ¬[-A]

    sealed trait TSet {
      type Compound[A]
      type Map[F[_]] <: TSet
    }

    sealed trait ∅ extends TSet {
      type Compound[A] = A
      type Map[F[_]] = ∅
    }

    // Note that this type is left-associative for the sake of concision.
    sealed trait ∨[T <: TSet, H] extends TSet {
      // Given a type of the form `∅ ∨ A ∨ B ∨ ...` and parameter `X`, we want to produce the type
      // `¬[A] with ¬[B] with ... <:< ¬[X]`.
      type Member[X] = T#Map[¬]#Compound[¬[H]] <:< ¬[X]

      // This could be generalized as a fold, but for concision we leave it as is.
      type Compound[A] = T#Compound[H with A]

      type Map[F[_]] = T#Map[F] ∨ F[H]
    }

    def foo[A : (∅ ∨ String ∨ Int ∨ List[Int])#Member](a: A): String = a match {
      case s: String => "String"
      case i: Int => "Int"
      case l: List[_] => "List[Int]"
    }


    def geza[A : (∅ ∨ String ∨ Int ∨ List[Int])#Member] : A = "45" // does not work 


    foo(geza)

    foo(42)
    foo("bar")
    foo(List(1, 2, 3))
//    foo(42d) // error
//    foo[Any](???) // error
  }

}

推荐答案

Scala.js的联合类型(

The union type of Scala.js (source and tests) supports A | B subtype of A | B | C. It even supports permutations like A | B subtype of B | C | A.

这篇关于标量中scala中的联合类型:A | B <:A | B | C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆