所以首先我很抱歉问this question。但是“逃离Zurg”的文章帮助了我很多,我可以为狼山羊白菜问题写出自己的解决方案。我正在下面放置我的代码。我希望你能告诉我F#狼山羊卷心菜
- 如果我的代码是写在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
对我来说看起来很实用。可能与我在Scheme中写的风格相同。 – leppie 2012-07-15 08:47:06
首选在F#中将printfn添加到Console.WriteLine。 – Asik 2012-07-15 20:31:13
@Dr_Asik:当没有格式说明符时,首选'stdout.WriteLine'到F#中的'printfn'。 ; - ] – ildjarn 2012-07-16 07:34:41