f#匹配表达式

编程入门 行业动态 更新时间:2024-10-23 03:25:35
本文介绍了f#匹配表达式-“规则将永远不会匹配"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试学习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#匹配表达式

本文发布于:2023-11-17 03:10:26,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1608601.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:表达式

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!