我试图在莫斯科ml中减去两个函数(都是类型为real).然后它说"重载 - 不能应用于真实类型的参数 - >真实.那么我应该如何编写函数?
fun CircleArea x = x*x*Math.pi
fun SquareArea x:real = 4*x*x
fun Area x = SquareArea - CircleArea
Run Code Online (Sandbox Code Playgroud)
您可能实际上并不想从另一个函数中减去一个函数,而是应用这些函数的返回值.您可以通过以下方式实现此目的:
fun Area x = (SquareArea x) - (CircleArea x)
Run Code Online (Sandbox Code Playgroud)
括号不是强制性的,因为函数应用(即,之间的空间SquareArea和x)结合比任何二进制运算符,包括更严格-.
您应该考虑在ML中使用以下命名约定:常规函数具有小写的起始符号,而代数类型的值构造函数具有大写的起始符号.例如:
fun area x = squareArea x - circleArea x
Run Code Online (Sandbox Code Playgroud)
但:
datatype shape = Square of int * int
| Circle of int
Run Code Online (Sandbox Code Playgroud)