Usage of the ref function in ML

不打扰是莪最后的温柔 提交于 2020-05-29 06:46:11

问题


Considering the ref operator I'm having trouble to understand its application and the sense of the follow instructions:

1.

In this definition what am I defining?

 - val ref x=ref 9;

 val x = 9 : int

2.

and here what am I doing with ref x:= ref 12?

 - val x= ref 8;

 val x = ref 8 : int ref

 - ref x := ref 12; 

 val it = () : unit

 - x;

 val it = ref 8 : int ref

回答1:


val ref x = ref 9 defines x to be 9 - just as if you had written val x = 9. This is because ref is a constructor, so it's pattern matching the value ref 9 against the pattern ref x, which binds x to 9. Of course writing it like this instead of just writing val x = 9 makes very little sense.

When you write ref x := ref 12, you create a new ref (of type int ref ref) that refers to x. You then immediately change that new ref to refer to ref 12 rather than to x. Since the new ref you created is never stored anywhere where you might access, this will have no observable effect.




回答2:


@newacct, @sepp2k I see this is from several years ago, but I found the discussion useful and wanted to contribute this output from Standard ML of New Jersey v110.79 [built: Tue Aug 8 16:57:33 2017]:

- val ref x = ref 9;
val x = 9 : int


来源:https://stackoverflow.com/questions/16134306/usage-of-the-ref-function-in-ml

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!