初めに、このような質問をして申し訳ありません。しかし、「Zurg からの脱出」の記事は私を大いに助け、オオカミやぎのキャベツ問題に対する独自の解決策を書くことができました。私は自分のコードを下に置いています。教えてほしい
- 私のコードが F# と関数型プログラミングの真の精神で書かれている場合
それは問題に対する最適で良い解決策です
open System (* The type direction determines which direction the human is present. Left means that Human is present on the left side of the bank. Right means human is present on the right side of the bank. *) type Direction = | Left | Right (* Master list of animals *) let Animals = ["Wolf"; "Goat"; "Cabbage"] let DeadlyCombinations = [["Wolf"; "Goat"];["Goat"; "Cabbage"];] let isMoveDeadly list1 list2 = List.exists (fun n -> n = list1) list2 let rec MoveRight animals = match animals with | [] -> [] | head::tail -> if (isMoveDeadly tail DeadlyCombinations) then MoveRight tail @ [head] else Console.WriteLine("Going to move " + head) tail let ListDiff list1 list2 = List.filter (fun n -> List.forall (fun x -> x <> n) list1) list2 let MoveLeft animals = let RightList = ListDiff animals Animals let ShouldTakeAnimal = isMoveDeadly RightList DeadlyCombinations if (ShouldTakeAnimal) then let x = List.head RightList Console.WriteLine("Going to move " + x + " back") [x] else Console.WriteLine("Farmer goes back alone") [] let rec Solve direction animals = match animals with | [] -> Console.WriteLine("Solved") | _ -> match direction with | Left -> Solve Right (MoveRight animals) | Right -> Solve Left (animals @ (MoveLeft animals)) [<EntryPoint>] let main args = Solve Left Animals 0