gpt4 book ai didi

f# - 有没有办法在 F# 中封装模式?

转载 作者:行者123 更新时间:2023-12-04 18:30:08 24 4
gpt4 key购买 nike

有没有办法在 F# 中封装模式?

例如,而不是写这个......

let stringToMatch = "example1"

match stringToMatch with
| "example1" | "example2" | "example3" -> ...
| "example4" | "example5" | "example6" -> ...
| _ -> ...

有什么方法可以沿着这些方向完成某些事情......
let match1to3 = | "example1" | "example2" | "example3"
let match4to6 = | "example4" | "example5" | "example6"

match stringToMatch with
| match1to3 -> ...
| match4to6 -> ...
| _ -> ...

最佳答案

你可以用 Active Patterns 做到这一点:

let (|Match1to3|_|) text = 
match text with
| "example1" | "example2" | "example3" -> Some text
| _ -> None

let (|Match4to6|_|) text =
match text with
| "example4" | "example5" | "example6" -> Some text
| _ -> None

match stringToMatch with
| Match1to3 text -> ....
| Match4to6 text -> ....
| _ -> ...

关于f# - 有没有办法在 F# 中封装模式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39780668/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com