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

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

问题描述

在查看 F#、Ocaml 和其他函数式语言代码示例时,我注意到 let 关键字的使用频率很高.

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

  • 为什么需要它?为什么设计语言有它?
  • 你为什么不能把它去掉?例如:让 x=4 变成 x=4

推荐答案

在 F#(和 OCaml)中 let 是非常强大的结构,用于值绑定,它意味着赋予符号某种意义.这可能意味着各种事情:

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)

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

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

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

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)

这里,z 的值将是 36.虽然你可以发明一些不需要 let 关键字的语法,但我认为使用 let 只是让代码更具可读性.

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天全站免登陆