【发布时间】:2014-12-12 07:51:12
【问题描述】:
上下文:
在ocaml中,当取一个完整的list作为参数时,假设change方法遍历list,如果在@987654326中搜索variable成功@,然后我们将该变量的绑定更改为另一个值。现在,我的代码在底部,除了返回完整列表之外,它可以正确执行所有操作。
为清楚起见,最好将此列表视为包含元组的字典。
问题:
我的表达式如何保存正在接收的列表并返回它,在遍历它时?关于已识别的问题(见下文),仅返回列表的一部分:这是表达式中的根本缺陷,还是很容易修复?如果这是一个简单的解决方法,那么可以添加什么来将其用于最终返回?
代码:
let rec change key value dict =
match dict with
| [] -> [(key, value)] (*Adding to the dictionary*)
| (a,b) :: dict -> if compare a key = 0 then (a, value)::dict (*changing value*)
else change key value dict (*continue search*)
;;
代码示例:
# let list = [(1,2);(4,2);(2,1)];;
val list : (int * int) list = [(1, 2); (4, 2); (2, 1)]
# change 2 3 list;;
- : (int * int) list = [(2, 3)]
# change 1 1 list
;;
- : (int * int) list = [(1, 1); (4, 2); (2, 1)]
# change 4 1 list
;;
- : (int * int) list = [(4, 1); (2, 1)]
# change 7 1 list
;;
- : (int * int) list = [(7, 1)]
回答:
let rec change key value dict =
match dict with
| [] -> (key, value)::dict (*Adding to the dictionary*)
| (a,b) :: dict -> if compare a key = 0 then (a, value)::dict (*changing value*)
else (a,b)::change key value dict (*continue search*)
;;
如果您看到上述内容,在第五行的 else 语句中,添加了 (a,b)::,它以正确的方式进行递归。
【问题讨论】:
标签: ocaml list recursion dictionary ocaml