我正在尝试学习F#,但是到了某种程度,我不明白自己在做错什么.我写了以下代码:
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 | [],_ -> [] | _,[] -> []我遇到的问题是编译器告诉我match表达式的第二条规则将永远不会被匹配. 我要用第二条规则表达的是,当世界"列表的开头与度量不同时,我们将在示例中进行以下计算.
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?
推荐答案我认为您想要:
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 | [],_ -> [] | _,[] -> []您原始代码的问题是,子句measurement::row, p::rop的实际含义是:给定任何两个非空列表,将第一个元素的第一个元素分配给measurement并将其尾部分配给第一个是row.这将隐藏现有变量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).
when子句允许您将值分配给新变量m,然后显式检查m是否等于measurement.
The when clause allows you to assign the value to a new variable m and then explicitly check if m equals measurement.
更多推荐
f#匹配表达式
发布评论