F#与两个值匹配 [英] F# matching with two values

查看:66
本文介绍了F#与两个值匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是F#的新手,我想比较两个值的语法((匹配...和...)语法

I'm fairly new to F# and I wanted to compare two values with the (match ... with ...) syntax

当我尝试比较两个值时出现问题:

The problem arises when I attempt to compare two values like this:

let value1 = 19
let isValue1 y =
    match y with
    | value1 -> y + 1
    | _ -> y

我收到一条警告,指出永远不会到达代码的"| _-> y"部分.为什么会这样?

I get a warning that the "| _ -> y" portion of the code will never be reached. Why is this?

我知道我可以执行以下操作以使功能按我希望的方式工作:

I know that I can do the following to get the function to work the way I want it to:

let value1 = 19
let isValue1 y =
    match y with
    | _ when y = value1 -> true
    | _ -> false

这也很好

let value1 = 19
let isValue1 y =
    match y with
    | 19 -> true
    | _ -> false

我很好奇为什么我不能做到这一点,以及匹配如何真正起作用.

I'm just curious about why I can't do that, and how match actually works.

推荐答案

match语句中的value1被定义为新变量,其值设置为y(作为匹配项).您在上面定义的value1会被忽略,就像在C#函数中声明与类变量同名的局部变量一样.因此,第一个匹配条件将匹配所有内容,而不仅仅是先前定义的value1值,因此会出现错误.希望能澄清问题.

The value1 within the match statement is defined as a new variable, the value of which is set to y (as a match). The value1 you define just above is ignored, just as if you were declaring a local variable in a C# function with the same name as a class variable. For this reason, the first match condition will match everything, not just the previously defined value of value1, hence the error. Hope that clarifies matters.

这篇关于F#与两个值匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆