How to define “type disjunction” (union types)?

前端 未结 15 2400
温柔的废话
温柔的废话 2020-11-22 05:52

One way that has been suggested to deal with double definitions of overloaded methods is to replace overloading with pattern matching:

object Bar {
   def fo         


        
15条回答
  •  长发绾君心
    2020-11-22 06:31

    Miles Sabin describes a very nice way to get union type in his recent blog post Unboxed union types in Scala via the Curry-Howard isomorphism:

    He first defines negation of types as

    type ¬[A] = A => Nothing
    

    using De Morgan's law this allows him to define union types

    type ∨[T, U] = ¬[¬[T] with ¬[U]]
    

    With the following auxiliary constructs

    type ¬¬[A] = ¬[¬[A]]
    type |∨|[T, U] = { type λ[X] = ¬¬[X] <:< (T ∨ U) }
    

    you can write union types as follows:

    def size[T : (Int |∨| String)#λ](t : T) = t match {
        case i : Int => i
        case s : String => s.length
    }
    

提交回复
热议问题