本文介绍了SML中绑定的价值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以解释为什么ans在这里经过评估后的价值是16吗?这是一个正确的答案吗?

我认为答案3自我们调用函数f并发送值1和2作为函数f也不会看到值5和10,但我想我错了。

  val x = 1 

val y = 2

val f = fn y => x + y

val x = 5

val y = 10

val ans = fx + y


解决方案

您所看到的有时称为词法作用域。函数 f 是在 x 的特定绑定范围内定义的,该范围是唯一重要的范围了解 f 在调用 f 时会做什么。 x 在调用 f 的范围内具有不同含义的事实不会影响 f 本身。在函数式编程的情况下,其他任何内容都会违反。在一个绑定的范围内,如

  val x = 1 

应该可以自由地用 1 >。因此,您定义 f 应该与定义相同

  def fy = 1 + y 

的确如此。 p>

can someone please explain why is "ans" is bound to value of 16 in here after evaluation - this is a correct answer?

I thought the answer 3 since we're calling function f and sending values 1 and 2 as function f doesn't also see the values 5 and 10 but I guess I am wrong.

val x = 1

val y = 2

val f = fn y => x + y

val x = 5

val y = 10

val ans = f x + y
解决方案

What you are seeing is sometimes called lexical scoping. The function f was defined in the scope of a certain binding for x, that scope is the only scope that matters in understanding what f does when f is invoked. The fact that x has a different meaning in the scope in which f is invoked doesn't affect the meaning of f itself. In the context of functional programming anything else would violate referential transparency. In the scope of a binding such as

val x = 1

it should be possible to freely replace x by 1. Thus your definition of f should be equivalent to the definition:

def f y = 1 + y

as, indeed, it is.

这篇关于SML中绑定的价值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 22:33