F#:图案组合? [英] F#: Pattern Composition?

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

问题描述

我正在尝试编写一个组合其他两种模式的模式,但我不知道该怎么做。我的输入是字符串列表(文档);我有一个与文档标题匹配的模式和与文档主体匹配的模式。该模式应该与整个文档匹配,并返回标题和正文模式的结果。

I'm trying to write a pattern that composes two other patterns, but I'm not sure how to go about it. My input is a list of strings (a document); I have a pattern that matches the document header and a pattern that matches the document body. This pattern should match the entire document and return the results of the header and body patterns.

推荐答案

您可以使用&安培; 。你在你的问题上省略了一些细节,所以这里有一些代码,我假设有点类似于你在做什么。

You can run two patterns together using &. You left out some details in your question, so here's some code that I'm assuming is somewhat similar to what you are doing.

let (|Header|_|) (input:string) =
    if input.Length > 0 then
        Some <| Header (input.[0])
    else
        None

let (|Body|_|) (input:string) =
    if input.Length > 0 then
        Some <| Body (input.[1..])
    else
        None

第一个模式将获取一个字符串的第一个字符,第二个将返回除第一个字符以外的所有内容。以下代码演示了如何一起使用它们。

The first pattern will grab the first character of a string, and the second will return everything but the first character. The following code demonstrates how to use them together.

match "Hello!" with
| Header h & Body b -> printfn "FOUND: %A and %A" h b
| _ -> ()

打印出来: FOUND:'H'和ello!

这篇关于F#:图案组合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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