我正在尝试用 F# 编写一个字符串处理函数,如下所示:
let rec Process html =
match html with
| '-' :: '-' :: '>' :: tail -> ("→" |> List.of_seq) @ Process tail
| head :: tail -> head :: Process tail
| [] -> []
我针对多个元素的模式匹配表达式有点难看(整个 '-'::'-'::'>'
事物)。有什么办法可以让它变得更好吗?另外,如果我要处理大文本,我所做的事情是否高效?或者还有其他办法吗?
澄清:我的意思是,例如,能够编写如下内容:
match html with
| "-->" :: tail ->
最佳答案
我同意其他人的观点,即使用字符列表进行严格的字符串操作可能并不理想。但是,如果您想继续使用此方法,获得接近您所要求的内容的一种方法是定义事件模式。例如:
let rec (|Prefix|_|) s l =
if s = "" then
Some(Prefix l)
else
match l with
| c::(Prefix (s.Substring(1)) xs) when c = s.[0] -> Some(Prefix xs)
| _ -> None
然后你可以像这样使用它:
let rec Process html =
match html with
| Prefix "-->" tail -> ("→" |> List.of_seq) @ Process tail
| head :: tail -> head :: Process tail
| [] -> []
关于parsing - F# 中针对列表开头进行模式匹配的更简单方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/570899/