我一直在玩一個衆所周知的揹包問題。這一次 - 但是 - 我決定在F#中實現它,因爲我正在學習這門語言,並且發現它特別有趣。實施F#回溯
我設法實現了算法的主要部分,但我也需要回溯。不幸的是,我在網上找到的所有信息都使用了Haskell,我不知道(但;))。
作爲佔位符我實現使用可變變量 回溯(不進入多的詳細信息, 「組合(I,K)」 返回的部分解決方案對於i項和k的容量):
let output =
List.rev
[
let i = ref N
let k = ref K
// analize items starting with the last one
for item in Array.rev items do
match !k - item.Size with
// if size of i-th item is greater than current capacity...
| x when x < 0 -> i := !i - 1
// ... this means we haven't taken this item
yield 0
// otherwise we've got two cases
| x when x >= 0 -> let v1 = combinations (!i-1, !k) id
let vc = combinations (!i, !k) id
if v1 = vc then
// case 1: item hasn't been taken
i := !i - 1
yield 0
else
// case 2: item is contained in the optimal solution
i := !i - 1
k := x
yield 1
]
List.iter (fun x -> printf "%A " x) output
我相信在F#中有更好的方法來做到這一點(例如使用計算表達式)。我很樂意聽到關於如何在功能風格中實現這一點的任何提示/信息。
最後一件事:請記住我是新來的函數式編程,並儘量避免一些魔法表情像我發現:「一個單子是endofunctors類別幺半羣,有什麼問題」
:)
工作正常,我 - 感謝提示:)。 –