F#模式与字符串匹配 [英] F# pattern matching with string

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

问题描述

let rec matchs str currList =
    match currList with 
    | [] -> []
    | (str, _) as hd :: tl -> hd :: matchs str tl
    | _::tl -> matchs str tl

我在这里有函数,当我尝试使用此行执行它时:

I have my function here, and when i try to execute it with this line:

matchs "A" [("A",5); ("BB",6); ("AA",9); ("A",0)];;

这是给定的输出

val it : (string * int) list = [("A", 5); ("BB", 6); ("AA", 9); ("A", 0)]

我不明白为什么它不只给我匹配"A"的元组.

I am not understanding why its not giving me only the tuples matching "A"

最终我希望我的输出是

val it : int list = [0; 5]

推荐答案

TL; DR:您不能匹配变量内容,只能匹配文字和构造函数(以及有效模式).

TL;DR: you can't match on variable content, only on literals and constructors (well, and active patterns).

此匹配项:

| (str, _) as hd :: tl -> 

与您的直觉相反,它并不只匹配以 str 作为第一组成部分的元组.相反,它匹配 any 元组,然后将这些元组的第一个组件绑定到名称 str ,从而遮盖了相同名称的功能参数.

Contrary to your intuition, it doesn't match only tuples that have str as first component. Instead, it matches any tuples, and then it binds those tuples' first component to name str, shadowing the function parameter of the same name.

这是此问题的简化版本:

Here's a simplified version of this problem:

let x = 42
let y = 5

match y with
| x -> printfn "%d" x
| _ -> printfn "not equal to x"

该代码将打印出"5",而不是"42".并且您会收到一个编译器警告,将永远不会达到第二个匹配情况.

This code would print out "5", not "42". And you get a compiler warning that the second match case will never be reached.

如果只希望第一个成分为 str 的元组,则可以在模式中使用 when 防护:

If you want only tuples with str first component, you can use a when guard with your pattern:

| (s, _) as hd :: tl when s == str -> 

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

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