Sml 使用ml-lex构建词法分析器

Sml 使用ml-lex构建词法分析器,sml,ml,ml-lex,Sml,Ml,Ml Lex,我需要创建一个绑定到标准输入流的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

我需要创建一个绑定到标准输入流的
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
是我的源代码中的函数名)

返回一个
字符串选项
,我猜应该是
字符串

您要做的是让
makeLexer
使用
字符串选项
,如下所示:

fun makeLexer  NONE    = <whatever you want to do when stream is empty>
  | makeLexer (SOME s) = <the normal body makeLexer, working on the string s>
获取选项类型并将其解压缩


请注意,由于当流为空时,
inputLine
返回
NONE
,因此最好使用第一种方法,而不是第二种方法。

的第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页)也展示了如何在整体上使用它

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

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