F#中列表开始的模式匹配更简单的方法

Dmi*_*ruk 2 f# parsing list pattern-matching

我正在尝试在F#中编写一个字符串处理函数,如下所示:

let rec Process html =
  match html with
  | '-' :: '-' :: '>' :: tail -> ("→" |> List.of_seq) @ Process tail
  | head :: tail -> head :: Process tail
  | [] -> []
Run Code Online (Sandbox Code Playgroud)

我的模式匹配表达式对几个元素有点难看(整个'-' :: '-' :: '>'事情).有没有办法让它变得更好?另外,如果我要处理大型文本,我的效率是多少?或者还有另一种方式吗?

澄清:我的意思是,例如,能够写出这样的东西:

match html with
| "-->" :: tail -> 
Run Code Online (Sandbox Code Playgroud)

kvb*_*kvb 5

我同意其他人认为使用字符列表进行严格的字符串操作可能并不理想.但是,如果您想继续使用这种方法,那么获得接近您要求的东西的一种方法是定义活动模式.例如:

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
Run Code Online (Sandbox Code Playgroud)

然后你就可以使用它:

let rec Process html =  
  match html with  
  | Prefix "-->" tail -> ("→" |> List.of_seq) @ Process tail  
  | head :: tail -> head :: Process tail  
  | [] -> []
Run Code Online (Sandbox Code Playgroud)