我是 f# 新手,正在编写一个程序来求解 xuvat 方程,但是编译器无法识别我的函数,并且出现错误The value or constructor 'xuvat' is not defined.
这是我的功能:
let xuvat xuvatTuple =
match xuvatTuple with
| (x, u, v, a, t) ->
match ((x<>null), (u<>null), (v<>null), (a<>null), (t<>null)) with
| (true, true, true, _, _) -> (x, u, v, ((v**2 - u**2)/(2*x)), ((2*x)/(u + v)))
| (true, true, _, true, _) -> (x, u, (u + a*t), a, ((sqrt (u**2 + (2 * a * x)) - u) / a))
| (true, _, true, true, _) -> (x, (v - (a*t)), v, a, ((v - sqrt (v**2 - (2 * a * x))) / a))
| (_, true, true, true, _) -> (((u**2 + v**2)/2*a), u, v, a, ((v-u)/a))
| (_, true, true, _, true) -> (((u+v)/2), u, v, ((v-u)/t), t)
| (_, true, _, true, true) -> ((u*t + (a*t*t)/2), u, (u + a*t), a, t)
| (_, _, true, true, true) -> ((v*t - (a*t*t)/2), (v - a*t), v, a, t)
| (true, _, _, true, true) -> (x, ((x - a*t*t)/2*t), ((x + a*t*t)/2*t), a, t)
| (true, _, true, _, true) -> (x, (((2*x)/t) + v), v, ((2*v*t-2*x)/t**2), t)
//| (true, true, _, _, true) -> (x, u, (((2*x)/t) - u), ((2*x -2*u*t)/t**2), t)
| _ -> failwith "NOT ENOUGH INFORMATION"
Run Code Online (Sandbox Code Playgroud)
这是我的代码的入口点以及调用我的函数的地方:
[<EntryPoint>]
let main argv =
let xuvatTuple = (7, 0, null, null, 4)
let finalTuple = xuvat xuvatTuple
printfn $"{finalTuple}"
Run Code Online (Sandbox Code Playgroud)
请你帮我找到答案。
主要问题不是该xuvat函数未被识别,而是该函数xuvat存在类型错误,因此编译器不接受它(因此后来未定义该函数)。
当我将代码复制到 Visual Studio 中时,它实际上并没有显示错误(在 IntelliSense 中),而是仅在我尝试编译它时显示错误,这很令人困惑。
问题是您正在接受一些参数(作为元组)并对它们进行数值运算,但还将它们与null. 但数字类型不允许null值,所以这不起作用。同样,您xuvatTuple包含一些int值和一些obj值,这也可能不是您想要的。
您可以通过使用option值来解决此问题:
let xuvat xuvatTuple =
match xuvatTuple with
| (Some x, Some u, Some v, _, _) ->
(x, u, v, ((v*v - u*u)/(2*x)), ((2*x)/(u + v)))
let xuvatTuple = (Some 7, Some 0, None, None, Some 4)
let finalTuple = xuvat xuvatTuple
Run Code Online (Sandbox Code Playgroud)
我只完成了第一个案例,但你明白了。我认为你的第二种情况也有一个错误,因为你的计算引用的是t,但这应该是null(如果你使用像这样的模式匹配,你会立即看到!)我也更改u**2为u*u,因为**没有在整数上定义。