【问题标题】:Parser combinators prevent mapping of strings解析器组合器阻止字符串的映射
【发布时间】:2016-02-20 16:39:50
【问题描述】:
import scala.util.parsing.combinator._

object SimpleArith extends JavaTokenParsers {
    "abc".map(identity)

产生

类型不匹配;找到 : String("abc") required: ?{def map: ?} 注意 隐式转换不适用,因为它们是 模棱两可:对象 Predef 类型中的两个方法 augmentString (x: String)scala.collection.immutable.StringOps 和方法字面量在 (s: String)SimpleArith.Parser[String] 类型的 trait RegexParsers 是 从 String("abc") 到 ?{def map: ?}

的可能转换函数

你是如何解决的?

【问题讨论】:

    标签: scala implicit-conversion ambiguous parser-combinators implicits


    【解决方案1】:

    我能想到三种方法。首先,您可以调用特定的所需隐式函数(它总是可以显式使用):

    augmentString("abc").map(identity)
    

    其次,强制转换为所需的类型(这需要您导入scala.collection.immutable.StringOps,或指定完全限定的类名):

    ("abc": StringOps).map(identity)
    

    第三,您可以将.map 或其他字符串操作代码移动到解析器隐式超出范围的其他方法中,然后调用该方法。例如:

    trait StringMappings {
      def mapStr(str: String) = str.map(identity)
    }
    

    import scala.util.parsing.combinator._
    
    object SimpleArith extends JavaTokenParsers with StringMappings {
      mapStr("abc")
    }
    

    【讨论】:

      【解决方案2】:

      不是最有效的,但任何像我这样的菜鸟都可以使用 toList of char

      str.toList.map ...
      

      【讨论】:

        猜你喜欢
        • 2023-03-15
        • 1970-01-01
        • 2015-07-12
        • 1970-01-01
        • 2010-09-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多