ML 表达式,逐行帮助
val y=2;
fun f(x) = x*y;
fun g(h) = let val y=5 in 3+h(y) end;
let val y=3 in g(f) end;
我正在寻找逐行解释。我是机器学习新手,正在尝试破译一些在线代码。另外,对“let/in”命令的描述也会非常有帮助。
val y=2;
fun f(x) = x*y;
fun g(h) = let val y=5 in 3+h(y) end;
let val y=3 in g(f) end;
I'm looking for a line by line explanation. I'm new to ML and trying to decipher some online code. Also, a description of the "let/in" commands would be very helpful.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我对 ocaml 更熟悉,但对我来说看起来都一样。
前两行绑定变量
y
和f
。y
为整数2
,f
为一个函数,该函数接受整数x
并将其乘以所绑定的值y
,2
。因此,您可以认为函数f
接受一些整数并将其乘以2
。 (f(x) = x*2
)下一行定义了一个函数
g
,它需要一些h
(结果是一个函数)它接受一个整数并返回一个整数)并执行以下操作:5
绑定到临时变量y
。let
/in
/end
语法视为声明可在表达式中使用的临时变量的方法紧随中
。end
只是结束表达式。 (这与省略end
的 ocaml 形成对比)3
加上应用参数y< 的函数
h
之和/code> 或5
。在较高层次上,函数
g
接受某个函数,将5
应用于该函数,并将3
添加到结果中。 (g(h) = 3+h(5)
)此时,环境中绑定了三个变量:
y = 2
、f = function< /code> 和
g = 函数
。现在,
3
绑定到临时变量y
并以函数f
作为参数调用函数g
。您需要记住,定义函数时,它会保留其环境,因此此处y
的临时绑定不会影响函数g
和f。他们的行为没有改变。
g
(g(h) = 3+h(5)
),使用参数f
调用 (f(x) = x*2
)。执行参数h
的替换,g
变为3+((5)*2)
,其计算结果为13
。我希望你清楚这一点。
I'm more familiar with ocaml but it all looks the same to me.
The first two lines bind variables
y
andf
.y
to an integer2
andf
to a function which takes an integerx
and multiplies it by what's bound toy
,2
. So you can think of the functionf
takes some integer and multiplies it by2
. (f(x) = x*2
)The next line defines a function
g
which takes someh
(which turns out to be a function which takes an integer and returns an integer) and does the following:5
to a temporary variabley
.let
/in
/end
syntax as a way to declare a temporary variable which could be used in the expression followingin
.end
just ends the expression. (this is in contrast to ocaml whereend
is omitted)3
plus the functionh
applying the argumenty
, or5
.At a high level, the function
g
takes some function, applies5
to that function and adds3
to the result. (g(h) = 3+h(5)
)At this point, three variables are bound in the environment:
y = 2
,f = function
andg = function
.Now
3
is bound to a temporary variabley
and calls functiong
with the functionf
as the argument. You need to remember that when a function is defined, it keeps it's environment along with it so the temporary binding ofy
here has no affect on the functionsg
andf
. Their behavior does not change.g
(g(h) = 3+h(5)
), is called with argumentf
(f(x) = x*2
). Performing the substitutions for parameterh
,g
becomes3+((5)*2)
which evaluates to13
.I hope this is clear to you.