问题
I'm trying to learn F# and I've come to a point where I don't understand what I am doing wrong. I wrote the following code:
let p = 0.2::0.2::0.2::0.2::0.2::[]
let world = "g"::"r"::"r"::"g"::"g"::[]
let measurements = "r"::"g"::[]
let pHit = 0.6
let pMiss = 0.2
let rec sense world probs measurement =
match world, probs with
| measurement::row, p::rop -> (p*pHit)::sense row rop measurement
| _::row, p::rop -> (p*pMiss)::sense row rop measurement
| [],_ -> []
| _,[] -> []
The problem I got is that compiler is telling me that the second rule of the match expression will never be matched. What I'm trying to express with second rule is that when the head of "world" list is different than measurement, we shall do the calculation as follows in the example.
Could anyone give me a hint with this one?
回答1:
I think you want:
let rec sense world probs measurement =
match world, probs with
| m::row, p::rop when m = measurement -> (p*pHit)::sense row rop measurement
| _::row, p::rop -> (p*pMiss)::sense row rop measurement
| [],_ -> []
| _,[] -> []
The problem with your original code is that the clause measurement::row, p::rop
actually means: given any two non-empty lists, assign the first element of the first one to measurement
and the tail of the first one to row
. This hides the existing variable measurement
and defines a new one (rather than checking that the value of the input equals to an existing variable).
The when
clause allows you to assign the value to a new variable m
and then explicitly check if m
equals measurement
.
来源:https://stackoverflow.com/questions/18984535/f-match-expression-rule-will-never-be-matched