Here's the entire code for the "calculator" program. I _did not_ author the code. The author is presumably another PhD in CS somewhere on this planet. https://programming.muthu.co/posts/beginners-guide-to-standard-ml/
[quote] fun add (x: real, y: real) = x + y; fun subtract (x: real, y: real) = x - y; fun multiply (x: real, y: real) = x * y; fun divide (x: real, y: real) = if y = 0.0 then raise DivByZero else x / y; exception DivByZero;
fun calculate (op: string, x: real, y: real) = case op of "+" => add(x, y) | "-" => subtract(x, y) | "*" => multiply(x, y) | "/" => divide(x, y) | _ => raise UnknownOp; exception UnknownOp;
(* Simple interaction loop (can be improved with more robust input handling) *) fun main() = let val input = TextIO.inputLine TextIO.stdIn; val [op, xStr, yStr] = String.tokens (fn c => c = ' ') input; val x = Real.fromString xStr; val y = Real.fromString yStr; in (case calculate(op, x, y) of SOME result => print ("Result: " ^ Real.toString result ^ "\n") | NONE => print ("Invalid operation\n")); main() end
handle DivByZero => print ("Division by zero error!\n") | UnknownOp => print ("Unknown operation!\n");
main();
[/quote]
the error returned is:
[quote] $ poly --use calc.sml Poly/ML 5.9.2 Release val add = fn: real * real -> real val subtract = fn: real * real -> real val multiply = fn: real * real -> real calc.sml:4: error: Type error in function application. Function: = : ''a * ''a -> bool Argument: (y, 0.0) : real * ''a Reason: Can't unify ''a to real (Requires equality type) Found near if y = 0.0 then raise DivByZero else x / y calc.sml:4: error: Value or constructor (DivByZero) has not been declared Found near raise DivByZero Error trying to use the file: 'calc.sml' [/quote]
Just trying to get the hang of the syntax - but the SML implementations seem to vary one from each other. As a result the code in some docs are applicable to one incantation but bombs out on others. A noob is walking a mine field trying to learn SML.
Back in the olden days - on USENET - "plonk" was always at hand, and this is what I'm about to do with SML - unless I can my shit together with a SML implementation and its accompanying resource that is not a PhD thesis, but a plebian how-to. I'm open to suggestions! TIA ...