F # match expression - "the rule will never match"

I am trying to learn F # and I have come to the conclusion that I do not 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 the compiler tells me that the second rule of the match expression will never be consistent. What I am trying to express with the second rule is that when the head of the "world" list is different from the dimension, we will do the calculation as follows in the example.

Can anyone give me a hint with this?

+1
f #
source share
1 answer

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 source code is that the sentence measurement::row, p::rop actually means: if any two non-empty lists are given, assign the first element of the first measurement element and the tail of the first one row , This hides the existing measurement variable and defines a new one (instead of checking that the input value is equal to the existing variable).

The when clause allows you to assign a value to a new variable m , and then explicitly check if m measurement matches.

+8
source share

All Articles