Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simpler way of pattern matching against start of list in F#

I'm trying to write a string processing function in F#, which looks like this:

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

My pattern matching expression against several elements is a bit ugly (the whole '-' :: '-' :: '>' thing). Is there any way to make it better? Also, is what I'm doing efficient if I were to process large texts? Or is there another way?

Clarification: what I mean is, e.g., being able to write something like this:

match html with
| "-->" :: tail -> 
like image 806
Dmitri Nesteruk Avatar asked Jan 26 '26 22:01

Dmitri Nesteruk


1 Answers

I agree with others that using a list of characters for doing serious string manipulation is probably not ideal. However, if you'd like to continue to use this approach, one way to get something close to what you're asking for is to define an active pattern. For instance:

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

Then you can use it like:

let rec Process html =  
  match html with  
  | Prefix "-->" tail -> ("→" |> List.of_seq) @ Process tail  
  | head :: tail -> head :: Process tail  
  | [] -> []
like image 136
kvb Avatar answered Jan 29 '26 11:01

kvb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!