Real life examples of Scala infix types

后端 未结 3 1902
南方客
南方客 2021-01-03 06:36

I\'ve found one interesting syntax stuff. It\'s called Infix type.

Example:

class M[T, U]
new (Int M String)

And now I

相关标签:
3条回答
  • 2021-01-03 07:08

    In scala library there is a class named ::. It is used so you could match the list like this:

    def m(l : List[Int]) = l match {
      case a :: b => println("Matched")        // The same as case ::(a, b) => ...
      case _ => println("Not matched")
    }
    

    There are lots of other examples in libraries like scalaz I think, but this one is the most canonical.

    Updated

    Just understood that it is not exactly what you wanted - you wanted types. Was adding =:= and <:< to the answer, but @johny was faster. Please see his answer

    0 讨论(0)
  • 2021-01-03 07:17

    From scala language, generalized type constraints

    =:=  =>  A=:=String => A must be String
    <:<  =>  A<:<String => A must be subtype of String
    
    0 讨论(0)
  • 2021-01-03 07:18

    shapeless library

    has bunch of them

    Polymorphic functions

    Set ~> Option
    

    Much like

    Set[A] => Option[A] forAny {type A}
    

    HLists

    Int :: String :: Double :: HNil 
    

    is like a super-flexible version of

    (Int, (String, (Double, ())))
    

    Coproducts

    Int :+: String :+: Double :+: CNil
    

    is like super-flexible version of

    Either[Int, Either[String, Either[Double, Nothing]]]
    

    Type tags

    Int @@ NonNegative
    

    Is zero-cost runtime analog of Int with some information remembered in tag type

    scalaz library

    as Archeg mentioned has even more of them

    Either

    String \/ Long
    

    Is cooler version of scala's Either[String,Long], read more here

    These

    Boolean \&/ Long
    

    Is handy implementation of

    Either[(Boolean, Long), Either[Boolean, Long]]
    

    Map

    String ==>> Double
    

    is haskellest version of

    collection.immutable.TreeMap[String, Double]
    

    Monoid Coproduct

    String :+: Float
    

    is alternated list of things, where similar things are aggregated (added, concatenated, choosed max, etc.) instead of sequencing

    0 讨论(0)
提交回复
热议问题