什么是“让” F#和OCaml等函数式语言中的关键字? [英] What is the "let" keyword in functional languages like F# and OCaml for?

查看:97
本文介绍了什么是“让” F#和OCaml等函数式语言中的关键字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在查看F#,Ocaml和其他函数式语言代码示例时,我注意到let关键字经常被使用。


  • 为什么你需要它?为什么要设计语言?

  • 为什么你不能把它抛出?例如:let x = 4变成x = 4

  • let 是一个非常强大的构造,用于值绑定,这意味着为符号赋予一些含义。这可能意味着各种各样的事情:



    声明本地或全局值 - 您可以使用它来声明本地值。这与在命令式语言中创建变量类似,不同之处在于变量的值以后不能更改(它是不可变的):

      let hello =Hello world
    printfn%shello

    声明函数 - 您也可以使用它来声明函数。在这种情况下,您可以指定一个符号是一个具有某种意义的函数:

      let add ab = a + b 
    printfn22 + 20 =%d(add 22 20)

    为什么你需要它?在F#中,如果没有它,代码将变得模糊不清。您可以使用值隐藏来创建隐藏前一个符号(具有相同名称)的新符号,例如以下返回 true

      let test()= 
    let x = 10
    let x = 20 //隐藏前面的'x '
    x = 20 //比较'x'与20并返回结果

    如果省略 let 关键字,您不知道您是在比较值还是在声明新符号。另外,正如其他人所指出的那样,您可以使用 let< symbol> =< expression>在< expression> 语法中(如果在F#中使用换行符,则在中不需要)将值绑定写入另一个表达式:

      let z =(let x = 3 + 3 in x * x)

    在这里, z 的值将是36.尽管您可能能够发明一些不需要 let 关键字的语法,我认为使用 let 可以让代码更具可读性。


    When looking at F#, Ocaml and other functional language code examples I notice that the let keyword is used very often.

    • Why do you need it? Why were the languages designed to have it?
    • Why can't you just leave it out? e.g: let x=4 becomes x=4

    解决方案

    In F# (and OCaml) let is quite powerful construct that is used for value binding, which means assigning some meaning to a symbol. This can mean various things:

    Declaring local or global value - you can use it for declaring local values. This is similar to creating a variable in imperative languages, with the exception that the value of the variable cannot be changed later (it is immutable):

    let hello = "Hello world"
    printfn "%s" hello
    

    Declaring function - you can also use it for declaring functions. In this case you specify that a symbol is a function with some arity:

    let add a b = a + b
    printfn "22 + 20 = %d" (add 22 20)
    

    Why do you need it? In F#, the code would be ambiguous without it. You can use value hiding to create new symbol that hides the previous symbol (with the same name), so for example the following returns true:

    let test () =
      let x = 10
      let x = 20 // hides previous 'x'
      x = 20     // compares 'x' with 20 and returns result
    

    If you omitted the let keyword, you wouldn't know whether you're comparing values or whether you're declaring a new symbol. Also, as noted by others, you can use the let <symbol> = <expression> in <expression> syntax (if you use line-break in F#, then you don't need in) to write value bindings as part of another expression:

    let z = (let x = 3 + 3 in x * x)
    

    Here, the value of z will be 36. Although you may be able to invent some syntax that doesn't require the let keyword, I think that using let simply makes the code more readable.

    这篇关于什么是“让” F#和OCaml等函数式语言中的关键字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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