我只是Ocaml的一个开始,我想研究图论,但是在Ocaml中实现。而且我遇到了麻烦:我只想使用深度优先搜索列出图表的连通组件。所以,我做了:
#open "stack" ;;
let non_empty pile =
try push (pop pile) pile ; true with Empty -> false ;;
let connected_comp g =
let already_seen = make_vect (vect_length g) false in
let comp = [] in
let dfs s lst =
let totreat = new () in
already_seen.(s) <- true; push s totreat;
let rec add_neighbour l = match l with
| [] -> ()
| q::r when already_seen.(q) = false -> push q totreat; already_seen.(q) <- true; add_neighbour r
| q::r -> add_neighbour r
in
while non_empty totreat do
let s = pop totreat in
already_seen.(s) <- true;
(* we want to add s to the list lst *) s::lst;
add_neighbour g.(s);
done
in
let rec head_list l = match l with
| [] -> failwith "Empty list"
| p::q -> p
in
let rec aux comp t = match t with
| t when t = vect_length g -> comp
| t when already_seen.(t) = true -> aux comp (t+1)
| t -> aux ((dfs t [])::comp) (t+1) (* we want that dfs t [] return the list lst modified *)
in aux comp 0;;
我获得了:
> | t -> (dfs t [])::comp ; aux comp (t+1) (* we want that dfs t [] return the list lst modified *)
> ^^^^^^^^^^^^^^^^
Warning : this expression is of type unit list,
but is used with the type unit.
connected_comp : int list vect -> unit list = <fun>
- : unit list = []
- : unit = ()
当然,我并不感到惊讶。但我想要做的是函数dfs
返回在参数(lst
列表)上发送的列表但是已修改,而这里并非如此,因为函数的类型为unit,导致它返回没有。但是在Ocaml中,由于语言是为了返回我认为的最后一个表达式,我不知道该怎么做。我也可以使用dfs
函数的递归算法,因为通过过滤,它将允许我返回列表,但我只是想了解Ocaml,并且如此修改(即使它不是最优的)我的算法
有人可以帮助我吗?
编辑:正如我们问我的那样,我会尝试减少我的代码并达到目的。所以,我有函数dfs
,它对应于深度优先搜索(对于图表)
let dfs s lst =
let totreat = new () in
already_seen.(s) <- true; push s totreat;
let rec add_neighbour l = match l with
| [] -> ()
| q::r when already_seen.(q) = false -> push q totreat; already_seen.(q) <- true; add_neighbour r
| q::r -> add_neighbour r
in
while non_empty totreat do
let s = pop totreat in
already_seen.(s) <- true;
(* we want to add s to the list lst *) s::lst;
add_neighbour g.(s);
done
in
(已经看过布尔的向量,先前定义过)
我唯一的问题是我希望函数返回修改后的列表lst
(在循环中),此时,它是一个单位函数。
我试图将lst定义为引用,但后来我不知道如何返回它......
我希望它更清楚,我现在对这一切并不熟悉......
谢谢!
答案 0 :(得分:0)
以下是您的代码的降级版本,它演示了一种方法来执行您想要的操作。
let non_empty _ = false
let dfs s lst =
let local_lst = ref lst in
while non_empty () do
(*do stuff here*)
let s = 1 in
local_lst := s::!local_lst;
(*do stuff here*)
done;
!local_lst
我首先将本地可变值local_lst
初始化为作为参数给出的列表lst
。然后我在while
循环中更新此值。最后我返回local_lst
中存储的值。