[英]F# won't pattern match all elements of a list
I wrote a recursive function, doMoves, that should match each element of a list and call the designated function. 我写了一个递归函数doMoves,它应匹配列表的每个元素并调用指定的函数。 However, I ran a list [Draw;
但是,我跑了一个清单[画; Draw] in which Draw function was only called once.
Draw]其中Draw函数只被调用一次。 I'm not sure why it doesn't match each element.
我不确定为什么它与每个元素都不匹配。
I've written a recursive function that should take the head of a list each step and match it with a function 我编写了一个递归函数,它应该在每一步都采用列表的头部并将其与函数匹配
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
I expected the output to state 我期望输出状态
Length of Drawn heldCards: 1
Length of Drawn heldCards: 2
but I get the following: 但我得到以下内容:
Length of Drawn heldCards: 1
The error is because DrawCard is a value, not a function. 错误是因为DrawCard是一个值,而不是一个函数。 To write a parameterless function in F# you need to specify unit as input.
要在F#中编写无参数函数,您需要指定单位作为输入。 ie
即
let drawCard () = //your implementation
I made an attempt to write what I think you are trying to do in a more functional manner: 我尝试用更实用的方式编写我认为你想要做的事情:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.