如何通过SML中的程序保留列表中的元素? [英] How to keep elements in list through out the program in SML?

查看:175
本文介绍了如何通过SML中的程序保留列表中的元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我必须每次调用一个函数来更新一个列表,这样列表的前一个元素才会被保留。



这是我的尝试:

 本地
val all_list = [];
in
fun insert(x:int):string = int2string(list_len(((all_list @ [x]))))
end;

问题是每次我插入时调用输出为1,表示该列表再次被初始化为 []

第一次调用插入的1,第二次调用的2,...等。



我无法提供解决方法。应该怎么做?

wiki / Side_effect_(computer_science)rel =nofollow noreferrer>副作用。
大多数功能程序员喜欢使用纯功能,而这些功能不有副作用。你的实现是一个纯函数,所以它会始终为相同的输入返回相同的值(在你的情况下,它会为任何输入返回相同的值)。



你可以通过使用引用来处理。



标准ML中引用的速成课程:


  • 使用 ref 创建一个新的引用, ref code>'a - > 'a ref ,因此它会将任意值打包到引用单元格中,您可以稍后修改该引用单元格;
  • 用于解包参考:(!):'a ref - > 'a ,在大多数命令式语言中,此操作是隐含的,但不在SML或OCaml中;

  • (:=):'a ref *'a - > unit 是一个用于修改引用的中缀运算符,下面是如何递增整数引用的内容: r:=!r + 1



以上代码给出了以下代码(我在前面加上 x 列表,而不是追加它们):

$ pre code $ local $ b $ val rxs = ref []
in
fun插入(x:int):string =
(rxs:= x ::!rxs;
Int.toString(length(!rxs)))
end


Suppose I have to update a list with each call to a function, such that, the previous element of the list are preserved.

Here is my attempt:

local 
    val all_list = [];
in
    fun insert (x:int) : string  = int2string (list_len( ((all_list@[x])) ) )
end;

The problem is that each time I call to insert, I get the output "1", which indicates that the list is initiated to [] again.

However I was expecting output of "1" for the first call to insert, and "2" for the second call,...etc.

I am not able to come with a workaround. How should it be done?

解决方案

You need to use side-effects. Most of the time functional programmers prefer to use pure functions, which don't have side effects. Your implementation is a pure function, so it will always return the same value for the same input (and in your case it returns the same value for any input).

You can deal with that by using a reference.

A crash course on references in Standard ML:

  • use ref to create a new reference, ref has type 'a -> 'a ref, so it packs an arbitrary value into a reference cell, which you can modify later;
  • ! is for unpacking a reference: (!) : 'a ref -> 'a, in most imperative languages this operation is implicit, but not in SML or OCaml;
  • (:=) : 'a ref * 'a -> unit is an infix operator used for modifying references, here is how you increment the contents of an integer reference: r := !r + 1.

The above gives us the following code (I prepend xs onto the list, instead of appending them):

local
    val rxs = ref []
in
    fun insert (x:int) : string =
      (rxs := x :: !rxs;
       Int.toString (length (!rxs)))
end

这篇关于如何通过SML中的程序保留列表中的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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