我是F#的初学者,这是我第一次尝试编写严肃的东西。对不起,代码有点长,但有一些我不明白的可变性问题。
这是Karger MinCut算法的一种实现,用于计算非有向图组件的最小割。我不会在这里讨论算法是如何工作的, 了解更多信息https://en.wikipedia.org/wiki/Karger%27s_algorithm 重要的是它是一个随机算法,运行确定数量的试运行,并采取“最佳”运行。
我现在意识到,如果我为每个随机试验构建一个特定的函数,我可以避免下面的许多问题,但我想完全理解下面的实现中的错误。
我在这个简单的图表上运行代码(当我们剪切图表时,mincut为2 分为2个分量(1,2,3,4)和(5,6,7,8),在这2个分量之间只有2个边缘)
3--4-----5--6
|\/| |\/|
|/\| |/\|
2--1-----7--8
文件simplegraph.txt
应对此图表进行编码,如下所示
(第1列=节点号,其他列=链接)
1 2 3 4 7
2 1 3 4
3 1 2 4
4 1 2 3 5
5 4 6 7 8
6 5 7 8
7 1 5 6 8
8 5 6 7
这段代码可能看起来太过于命令式编程,我很抱歉。
所以有一个主要的i循环调用每个试验。 第一次执行,(当i = 1时)看起来光滑而完美, 但是当i = 2时,我有运行时错误执行,因为它看起来有些变量, 像WG没有正确重新初始化,导致出界错误。
WG,WG1和WGmin是type wgraphobj
,它们是对象对象的记录
WG1在主循环外部定义,我不对WG1进行新的分配。
[但它的类型是可变的,唉]
我用指令
定义了第一个WGlet mutable WG = WG1
然后在for i循环的开头, 我写了
WG <- WG1
然后,我修改每个试验中的WG对象进行一些计算。 当试验结束并且我们进入下一次试验(我增加)时,我想将WG重置为其初始状态,如WG1。 但它似乎不起作用,我不明白为什么......
这是完整的代码
MyModule.fs [执行时不需要的一些功能]
namespace MyModule
module Dict =
open System.Collections.Generic
let toSeq d = d |> Seq.map (fun (KeyValue(k,v)) -> (k,v))
let toArray (d:IDictionary<_,_>) = d |> toSeq |> Seq.toArray
let toList (d:IDictionary<_,_>) = d |> toSeq |> Seq.toList
let ofMap (m:Map<'k,'v>) = new Dictionary<'k,'v>(m) :> IDictionary<'k,'v>
let ofList (l:('k * 'v) list) = new Dictionary<'k,'v>(l |> Map.ofList) :> IDictionary<'k,'v>
let ofSeq (s:('k * 'v) seq) = new Dictionary<'k,'v>(s |> Map.ofSeq) :> IDictionary<'k,'v>
let ofArray (a:('k * 'v) []) = new Dictionary<'k,'v>(a |> Map.ofArray) :> IDictionary<'k,'v>
Karger.fs
open MyModule.Dict
open System.IO
let x = File.ReadAllLines "\..\simplegraph.txt";;
// val x : string [] =
let splitAtTab (text:string)=
text.Split [|'\t';' '|]
let splitIntoKeyValue (s:seq<'T>) =
(Seq.head s, Seq.tail s)
let parseLine (line:string)=
line
|> splitAtTab
|> Array.filter (fun s -> not(s=""))
|> Array.map (fun s-> (int s))
|> Array.toSeq
|> splitIntoKeyValue
let y =
x |> Array.map parseLine
open System.Collections.Generic
// let graph = new Map <int, int array>
let graphD = new Dictionary<int,int seq>()
y |> Array.iter graphD.Add
let graphM = y |> Map.ofArray //immutable
let N = y.Length // number of nodes
let Nruns = 2
let remove_table = new Dictionary<int,bool>()
[for i in 1..N do yield (i,false)] |> List.iter remove_table.Add
// let remove_table = seq [|for a in 1 ..N -> false|] // plus court
let label_head_table = new Dictionary<int,int>()
[for i in 1..N do yield (i,i)] |> List.iter label_head_table.Add
let label = new Dictionary<int,int seq>()
[for i in 1..N do yield (i,[i])] |> List.iter label.Add
let mutable min_cut = 1000000
type wgraphobj =
{ Graph : Dictionary<int,int seq>
RemoveTable : Dictionary<int,bool>
Label : Dictionary<int,int seq>
LabelHead : Dictionary<int,int> }
let WG1 = {Graph = graphD;
RemoveTable = remove_table;
Label = label;
LabelHead = label_head_table}
let mutable WGmin = WG1
let IsNotRemoved x = //
match x with
| (i,false) -> true
| (i,true) -> false
let IsNotRemoved1 WG i = //
(i,WG.RemoveTable.[i]) |>IsNotRemoved
let GetLiveNode d =
let myfun x =
match x with
| (i,b) -> i
d |> toList |> List.filter IsNotRemoved |> List.map myfun
let rand = System.Random()
// subsets a dictionary given a sub_list of keys
let D_Subset (dict:Dictionary<'T,'U>) (sub_list:list<'T>) =
let z = Dictionary<'T,'U>() // create new empty dictionary
sub_list |> List.filter (fun k -> dict.ContainsKey k)
|> List.map (fun k -> (k, dict.[k]))
|> List.iter (fun s -> z.Add s)
z
// subsets a dictionary given a sub_list of keys to remove
let D_SubsetC (dict:Dictionary<'T,'U>) (sub_list:list<'T>) =
let z = dict
sub_list |> List.filter (fun k -> dict.ContainsKey k)
|> List.map (fun k -> (dict.Remove k)) |>ignore
z
// subsets a sequence by values in a sequence
let S_Subset (S:seq<'T>)(sub_list:seq<'T>) =
S |> Seq.filter (fun s-> Seq.exists (fun elem -> elem = s) sub_list)
let S_SubsetC (S:seq<'T>)(sub_list:seq<'T>) =
S |> Seq.filter (fun s-> not(Seq.exists (fun elem -> elem = s) sub_list))
[<EntryPoint>]
let main argv =
let mutable u = 0
let mutable v = 0
let mutable r = 0
let mutable N_cut = 1000000
let mutable cluster_A_min = seq [0]
let mutable cluster_B_min = seq [0]
let mutable WG = WG1
let mutable LiveNodeList = [0]
// when i = 2, i encounter problems with mutability
for i in 1 .. Nruns do
WG <- WG1
printfn "%d" i
for k in 1..(N-2) do
LiveNodeList <- GetLiveNode WG.RemoveTable
r <- rand.Next(0,N-k)
u <- LiveNodeList.[r] //selecting a live node
let uuu = WG.Graph.[u] |> Seq.map (fun s -> WG.LabelHead.[s] )
|> Seq.filter (IsNotRemoved1 WG)
|> Seq.distinct
let n_edge = uuu |> Seq.length
let x = rand.Next(1,n_edge)
let mutable ok = false //maybe we can take this out
while not(ok) do
// selecting the edge from node u
v <- WG.LabelHead.[Array.get (uuu |> Seq.toArray) (x-1)]
let vvv = WG.Graph.[v] |> Seq.map (fun s -> WG.LabelHead.[s] )
|> Seq.filter (IsNotRemoved1 WG)
|> Seq.distinct
let zzz = S_SubsetC (Seq.concat [uuu;vvv] |> Seq.distinct) [u;v]
WG.Graph.[u] <- zzz
let lab_u = WG.Label.[u]
let lab_v = WG.Label.[v]
WG.Label.[u] <- Seq.concat [lab_u;lab_v] |> Seq.distinct
if (k<N-1) then
WG.RemoveTable.[v]<-true
//updating Label_head for all members of Label.[v]
WG.LabelHead.[v]<- u
for j in WG.Label.[v] do
WG.LabelHead.[j]<- u
ok <- true
printfn "u= %d v=%d" u v
// end of for k in 1..(N-2)
// counting cuts
// u,v contain the 2 indexes of groupings
let cluster_A = WG.Label.[u]
let cluster_B = S_SubsetC (seq[for i in 1..N do yield i]) cluster_A // defined as complementary of A
// let WG2 = {Graph = D_Subset WG1.Graph (cluster_A |> Seq.toList)
// RemoveTable = remove_table
// Label = D_Subset WG1.Graph (cluster_A |> Seq.toList)
// LabelHead = label_head_table}
let cross_edge = // returns keyvalue pair (k,S')
let IsInCluster cluster (k,S) =
(k,S_Subset S cluster)
graphM |> toSeq |> Seq.map (IsInCluster cluster_B)
N_cut <-
cross_edge |> Seq.map (fun (k:int,v:int seq)-> Seq.length v)
|> Seq.sum
if (N_cut<min_cut) then
min_cut <- N_cut
WGmin <- WG
cluster_A_min <- cluster_A
cluster_B_min <- cluster_B
// end of for i in 1..Nruns
0 // return an integer exit code
算法的描述:(我认为它对解决我的问题不太重要)
在每次试验中,有几个步骤。在每一步,我们将2个节点合并为1,(有效地删除1)更新图形。我们这样做了6次,直到只剩下2个节点,我们将其定义为2个集群,然后我们查看这2个集群之间的交叉边数。如果我们“幸运”那么这两个集群将是(1,2,3,4)和(5,6,7,8),并找到正确的削减数量。 在每个步骤中,使用合并2个节点的效果更新对象WG 只有LiveNodes(由于合并2个节点而未被淘汰的那些)完全保持最新。
WG.Graph是更新的图表
WG.Label包含已合并到当前节点
的节点的标签WG.LabelHead包含该节点已合并到的节点的标签
WG.RemoveTable表示节点是否已被移除。
提前感谢愿意看一眼的人!
答案 0 :(得分:2)
&#34;它似乎不起作用&#34;,因为wgraphobj
是一个引用类型,它在堆栈上分配,这意味着当你改变{{1}的内部时},你也在改变WG
的内脏,因为它们是同一个内脏。
如果你使用可变状态,这正是你陷入困境的那种。这就是为什么人们建议不要使用它。特别是,您使用可变字典会破坏算法的稳健性。我建议使用F#自己的高效不可变词典(称为WG1
)。
现在,回应您对Map
发出编译错误的评论。
WG.Graph <- GraphD
是可变的,但WG
不是(但WG.Graph
的内容也是可变的)。有一点不同,让我试着解释一下。
WG.Graph
在某种意义上是可变的,它指向WG
类型的某个对象,但您可以在程序过程中指向另一个相同类型的对象。
wgraphobj
是 WG.Graph
内的字段。它指向WG
类型的某个对象。你不能使它指向另一个对象。您可以创建不同的Dictionary<_,_>
,其中字段wgraphobj
指向不同的字典,但您无法更改原始Graph
字段Graph
的位置。
为了使字段wgraphobj
本身可变,您可以将其声明为:
Graph
然后你就可以改变那个字段:
type wgraphobj = {
mutable Graph: Dictionary<int, int seq>
...
请注意,在这种情况下,不需要将值 WG.Graph <- GraphD
本身声明为WG
。
但是,在我看来,为了您的目的,您实际上可以创建一个更改字段mutable
的新实例wgraphobj
,并将其分配给可变引用{{1} }:
Graph