f# match expression - “rule will never be matched”

一世执手 提交于 2019-12-11 08:57:31

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!