我编写了一个递归函数doMoves,该函数应与列表的每个元素匹配并调用指定的函数。但是,我运行了一个列表[Draw; Draw],其中Draw函数仅被调用一次。我不确定为什么它与每个元素都不匹配。
我编写了一个递归函数,该函数应该将列表的每一步都放在头上,并将其与一个函数匹配
let officiate (cards:Card list) (moves:Move list) (goal:int) =
let mutable heldCards = []
let mutable deck = cards
let doNothing =
heldCards
let DrawCard =
lazy (
heldCards<-List.append heldCards [deck.Head]
List.length heldCards |> printfn "Length of Drawn heldCards: %d"
deck<-deck.Tail)
let rec doMoves movs =
match movs with
| [] -> doNothing
| x::xs ->
match x with
| Draw -> DrawCard.Force()
doMoves xs
doMoves moves
true
let moves = [Draw; Draw]
let cards = [(Jack,Clubs); (Num(8),Diamonds)]
let card = (Jack,Spades)
officiate cards moves 42
我希望输出状态
Length of Drawn heldCards: 1
Length of Drawn heldCards: 2
但是我得到以下信息:
Length of Drawn heldCards: 1
答案 0 :(得分:0)
错误是因为DrawCard是一个值,而不是一个函数。要在F#中编写无参数函数,您需要指定单位作为输入。即
let drawCard () = //your implementation
我试图用一种更实用的方式来写我认为你正在尝试的事情:
let officiate (cards:Card list) (moves:Move list) (goal:int) =
let drawCard (heldCards: Card list) (deck: Card list) =
match deck with
| [] -> Error "Empty deck"
| head::tail -> Ok (List.append heldCards [head], tail)
let rec doMoves heldCards deck movs =
printfn "Hand is %d, deck is %d." (List.length heldCards) (List.length deck)
match movs with
| [] -> heldCards, deck
| x::xs ->
match x with
| Draw ->
drawCard heldCards deck
|> function
| Ok (h, d) -> doMoves h d xs
| Error s ->
printfn "An error occurred: %s" s
heldCards, deck
| Discard c -> failwith "todo"
doMoves [] cards moves
let moves = [Draw; Draw]
let cards = [(Jack,Clubs); (Num(8),Diamonds)]
officiate cards moves 42