3

我需要创建一个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是我的源代码中存在的函数名称)

4

2 回答 2

3

inputLine返回 a string option,我的猜测是 astring是预期的。

您想要做的是makeLexer采取 a 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,因此使用第一种方法可能比第二种方法更好。

于 2011-01-25T13:31:06.297 回答
2

ML-Lex 和 ML-Yacc 用户指南的第 38 页(或论文中的第 32 页)给出了如何制作交互式流的示例

使用 inputLine 可以使示例代码更简单。因此,我将使用 Sebastian 给出的示例,请记住,如果用户按下 CTRL-D,至少使用 stdIn 时 inputLine 可能会返回 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 页)上的计算器示例显示了如何整体使用它

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

于 2011-01-26T08:11:57.977 回答