【问题标题】:Real life examples of Scala infix typesScala中缀类型的真实例子
【发布时间】:2015-10-26 23:24:50
【问题描述】:

我发现了一个有趣的语法东西。它叫做Infix type

例子:

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

现在我正在从一些流行的框架或库中寻找这种类型的示例。我在哪里可以找到它们?有什么建议吗?

【问题讨论】:

    标签: scala


    【解决方案1】:

    shapeless library

    有一堆

    Polymorphic functions

    Set ~> Option
    

    很像

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

    HLists

    Int :: String :: Double :: HNil 
    

    就像一个超级灵活的版本

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

    Coproducts

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

    就像是超级灵活的版本

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

    Type tags

    Int @@ NonNegative
    

    Int 的零成本运行时模拟,并在标签类型中记住了一些信息

    scalaz library

    正如 Archeg 提到的那样,它们还有更多

    Either

    String \/ Long
    

    是 scala 的 Either[String,Long] 的更酷版本,阅读更多 here

    These

    Boolean \&/ Long
    

    是否方便实现

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

    Map

    String ==>> Double
    

    是最简单的版本

    collection.immutable.TreeMap[String, Double]
    

    Monoid Coproduct

    String :+: Float
    

    是事物的交替列表,其中相似的事物被聚合(添加、连接、选择的最大值等)而不是排序

    【讨论】:

    • +1 不是因为中缀操作列表,而是因为这些库的亮点,我从来没有时间去思考。让内容更容易理解。
    【解决方案2】:

    来自 scala 语言,广义类型约束

    =:=  =>  A=:=String => A must be String
    <:<  =>  A<:<String => A must be subtype of String
    

    【讨论】:

      【解决方案3】:

      在 Scala 库中有一个名为 :: 的类。使用它以便您可以像这样匹配列表:

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

      我认为像 scalaz 这样的库中还有很多其他示例,但这个是最规范的。

      更新

      刚刚明白这不是您想要的——您想要的类型。正在将=:=&lt;:&lt; 添加到答案中,但@johny 更快。请看他的回答

      【讨论】:

        猜你喜欢
        • 2015-05-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-11-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多