我想在sml中创建堆栈,我尝试过使用列表;但我无法将元素添加到列表中。我试图从输入文件读取行,说如果行说:在sml中创建堆栈
push 5
push 9
add
quit
然后我想输出文件是:
14
因为5 + 9是14 到目前为止,我能够创建布尔函数来识别行是推还是数字。
fun is_digit (c) = #"0" <= c andalso c <= #"9";
fun is_Push (c) = String.isSubstring "push" c;
fun stack(inFile : string, outFile : string) =
let
val ins = TextIO.openIn inFile;
val outs = TextIO.openOut outFile;
val readLine = TextIO.inputLine ins;
val it = []: string list;
fun helper(readLine : string option) =
case readLine of
NONE => (TextIO.closeIn ins; TextIO.closeOut outs)
| SOME(c) => (
if is_Push c
then
let
val number = String.sub(c,5);
val numbChar = Char.toString number;
in
val myList = nil :: numbChar;
TextIO.output(outs, Int.toString(length myList))
end
else
TextIO.output(outs, "aaa\n");
helper(TextIO.inputLine ins))
in
helper(readLine)
end
正如其他地方所评论的,如果您将新元素添加到前面而不是后面,则列表是理想的堆栈。 'it = number :: it'。 –