Question: I have written a function in SML that is giving me this compilation error: Can you help me fix this code so i will not
I have written a function in SML that is giving me this compilation error: Can you help me fix this code so i will not get compilation errors when loading into the compiler.
datatype token = DI | EQ | ID of string | MI | PL | TI val isLetter = fn : char -> bool val isOp = fn : char -> bool val isWhiteSpace = fn : char -> bool val getOpToken = fn : char -> token p4.sml:35.10-35.15 Error: syntax error: replacing WHILE with EQUALOP [unexpected exception: Compile]
uncaught exception Compile [Compile: "syntax error"] raised at: ../compiler/Parse/main/smlfile.sml:19.24-19.46 ../compiler/TopLevel/interact/evalloop.sml:45.54 ../compiler/TopLevel/interact/evalloop.sml:306.20-306.23 ../compiler/TopLevel/interact/interact.sml:65.39-65.42
This is my SML code:
datatype token = ID of string | EQ | PL | MI | TI | DI;
(* Helper function to check if a character is a valid letter *)
fun isLetter(c: char) = c >= #"a" andalso c <= #"z" orelse c >= #"A" andalso c <= #"Z";
(* Helper function to check if a character is a valid operation character *)
fun isOp(c: char) = c = #"+" orelse c = #"-" orelse c = #"*" orelse c = #"/" orelse c = #"=";
(* Helper function to check if a character is whitespace *)
fun isWhiteSpace(c: char) = c = #" " orelse c = #"\t" orelse c = #" ";
(* Helper function to get the token of an operation character *)
fun getOpToken(c: char) : token =
if c = #"+" then PL
else if c = #"-" then MI
else if c = #"*" then TI
else if c = #"/" then DI
else EQ;
(* Main parse function *)
fun parse (fileName: string) : token list =
let
(* Read the file into a string *)
val file = TextIO.openIn fileName
val fileStr = TextIO.inputAll file
val len = String.size fileStr
(* Helper function to parse the string recursively *)
fun parseHelper (i: int, acc: token list) : token list =
if i = len then acc
else if isWhiteSpace(String.sub(fileStr, i)) then parseHelper(i + 1, acc)
else if isLetter(String.sub(fileStr, i)) then
(* Build the string of letters *)
let
val j = ref (i + 1)
while !j < len andalso isLetter(String.sub(fileStr, !j)) orelse j := !j + 1
val id = String.substring(fileStr, i, !j - i)
in parseHelper(!j, acc @ [ID id]) end
else if isOp(String.sub(fileStr, i)) then
parseHelper(i + 1, acc @ [getOpToken(String.sub(fileStr, i))])
else (* Invalid character *)
(print "Compilation error"; [])
in
TextIO.closeIn file;
parseHelper(0, [])
end;
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
