这是F#中的变量吗?
let print_scene (y, v) =
do Console.Clear()
let y, v = int y, int v (* This is the code in question *)
for j = 10 downto 0 do
for i = 0 to 30 do
if (y + 1) = j && i = 15 then
Console.Write("b")
elif j = 0 || i = 0 || j = 10 || i = 30 then
Console.Write("*")
else
Console.Write(" ")
Console.Write("\n")
ignore(Console.ReadKey())
我不明白 int
在此代码中的作用,含义或原因.
I don't understand what the int
is doing in this code, what it is, or why it's there.
实际上,这是参数屏蔽.
Indeed, this is parameter shadowing.
let foo bar =
let bar = bar * bar
bar
这在F#中绝对没问题.函数参数正在被绑定遮盖.一切都没有改变-只是使原始绑定不可访问.
This is absolutely fine in F#. A function parameter is being shadowed by a binding. Nothing is being changed - it just makes the original binding inaccessible.
更深层次的问题在于 int
.因为 int
将类型转换为 Int32
,所以您希望该函数接受任何可以转换为 int
的内容;数字或字符串.但是-
The deeper problem lies in the int
. Because int
converts a type to an Int32
you'd expect the function to take in anything that can be converted to int
; either numbers or strings.
But -
let print_scene (y, v) =
let y, v = int y, int v
()
print_scene (1.0, "2.0")
print_scene (1.0, 2.0) //this won't compile
函数参数将在首次使用时受到限制.在这里,其类型变为:
The function parameters will be constrained from its first usage. Here, its type becomes:
float * string -> unit
这是因为F#没有高级多态性.如果对您来说很重要,那么最好明确地声明要接受的参数的类型,或者对它进行内联.
This is because F# doesn't have higher-kinded polymorphism. You are probably better off being explicit about the type of parameters you want to accept, or inlining it, if being generic is important to you.
let inline print_scene (y, v) =
let y, v = int y, int v
()
print_scene (1.0, "2.0")
print_scene (1.0, 2.0) //this works