我正在写一个匹配,其中使用“ when”表达式来限制基于函数f的匹配。我想将f的结果绑定在以下表达式中使用。我希望我的代码看起来像这样:
match input with
| input when f x input -> //Some exp where (f x input) is used but not recomputed
| input when f y input -> //Some exp where (f x input) is used but not recomputed
显而易见的解决方案是简单地重新计算结果,但是我想知道是否可以使用其他机制。
答案 0 :(得分:0)
以下表达式中f的结果为“ true”。您可以根据需要使用true。如果您希望以某种方式进行匹配和转换匹配,则可以使用主动模式。
open System.Text.RegularExpressions
let (|FirstRegexGroup|_|) pattern input =
let m = Regex.Match(input,pattern)
if (m.Success) then Some m.Groups.[1].Value else None
let testRegex str =
match str with
| FirstRegexGroup "http://(.*?)/(.*)" host ->
printfn "The value is a url and the host is %s" host
| FirstRegexGroup ".*?@(.*)" host ->
printfn "The value is an email and the host is %s" host
| _ -> printfn "The value '%s' is something else" str
// test
testRegex "http://google.com/test"
testRegex "alice@hotmail.com"
来源https://fsharpforfunandprofit.com/posts/convenience-active-patterns/