这是F#中的变量吗? [英] Is this shadowing a variable in F#?

查看:57
本文介绍了这是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

这篇关于这是F#中的变量吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆