【问题标题】:building a lexical analyser using ml-lex使用 ml-lex 构建词法分析器
【发布时间】:2011-06-15 04:57:34
【问题描述】:

我需要创建一个绑定到标准输入流的 lexer 的新实例。
但是,当我输入

val lexer = makeLexer( fn n => inputLine( stdIn ) );

我收到一个我不明白的错误:

stdIn:1.5-11.13 Error: operator and operand don't agree [tycon mismatch]
  operator domain: int -> string
  operand:         int -> string option
  in expression:

makeLexer 是我源代码中的函数名)

【问题讨论】:

    标签: sml ml ml-lex


    【解决方案1】:

    inputLine 返回一个string option,我猜应该是string

    你想要做的是要么让makeLexer 取一个string option,就像这样:

    fun makeLexer  NONE    = <whatever you want to do when stream is empty>
      | makeLexer (SOME s) = <the normal body makeLexer, working on the string s>
    

    或将您的线路更改为:

    val lexer = makeLexer( fn n => valOf ( inputLine( stdIn ) ) );
    

    valOf 接受一个选项类型并将其解包。

    请注意,由于inputLine 在流为空时返回NONE,因此使用第一种方法可能比第二种方法更好。

    【讨论】:

      【解决方案2】:

      User's Guide to ML-Lex and ML-Yacc 的第 38 页(或论文中的第 32 页)给出了如何制作交互式流的示例

      使用 inputLine 可以使示例代码更简单。 因此,我将使用 Sebastian 给出的示例,请记住,如果用户按下 CTRL-D,则 inputLine 可能使用 stdIn 至少返回 NONE。

      val lexer =
      let 
        fun input f =
            case TextIO.inputLine f of
              SOME s => s
            | NONE => raise Fail "Implement proper error handling."
      in 
        Mlex.makeLexer (fn (n:int) => input TextIO.stdIn)
      end
      

      另外,第 40 页(论文中的 34 页)上的计算器示例显示了如何整体使用它

      一般来说,用户指南包含一些很好的示例和解释。

      【讨论】:

        猜你喜欢
        • 2017-08-22
        • 2010-11-02
        • 2021-11-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-09-18
        • 2012-05-17
        相关资源
        最近更新 更多