我正在使用F#完成Land of Lisp这本书的学习(是的,很奇怪)。在他们的第一个示例文本冒险游戏中,他们利用了全局变量的突变,而我想避免这种情况。我的Monad编程技能弱,所以现在我正在使用丑陋的状态传递方式:
let pickUp player thing (objects: Map<Location, Thing list>) =
let objs = objects.[player.Location]
let attempt = objs |> List.partition (fun o -> o.Name = thing)
match attempt with
| [], _ -> "You cannot get that.", player, objs
| thing :: _, things ->
let player' = { player with Objects = thing :: player.Objects }
let msg = sprintf "You are now carrying %s %s" thing.Article thing.Name
msg, player', things
let player = { Location = Room; Objects = [] }
let objects =
[Room, [{ Name = "whiskey"; Article = "some" }; { Name = "bucket"; Article = "a" }];
Garden, [{ Name = "chain"; Article = "a length of" }]]
|> Map.ofList
let msg, p', o' = pickUp player "bucket" objects
// etc.
如何因式分解显式状态以使代码更加简洁?(假设我可以访问状态单子类型,如果有帮助的话; 我知道在F#中有示例代码。)
我该如何将显式状态提取出来以使代码更加美观?(假设我可以访问State单子类型,如果有帮助的话;我知道在F#中有一些示例代码可用。)