Skip to content

Instantly share code, notes, and snippets.

@ebresafegaga
Last active March 28, 2023 16:00
Show Gist options
  • Save ebresafegaga/4d2afa5131384b47022077706b7ffae3 to your computer and use it in GitHub Desktop.
Save ebresafegaga/4d2afa5131384b47022077706b7ffae3 to your computer and use it in GitHub Desktop.
Camel to Kebab
(* camel_to_kebab('CamelCaseString') == 'camel-case-string'
camel_to_kebab('CamelCaseStringWithABREV') == 'camel-case-string-with-abrev'
camel_to_kebab('CamelCaseStringWithABREVInCenter') == 'camel-case-string-with-abrev-in-center' *)
(* words = re.findall('([A-Z][a-z]+)|([A-Z]+(?=[A-Z][a-z]+))', s) *)
type state =
| Start
| InsideCamel
| InsideAbrev
let rec words:
char list ->
state ->
char list ->
(char list) list ->
(char list) list =
fun str state chunk acc ->
match state, str with
| Start, ('A'..'Z'|'a'..'z' as c :: str) -> words str InsideCamel (c :: chunk) acc
| InsideCamel, ('a'..'z' as c :: str) -> words str InsideCamel (c :: chunk) acc
| InsideCamel, ('A'..'Z' :: 'A'..'Z' :: _) -> words str InsideAbrev [] (chunk :: acc)
| InsideCamel, ('A'..'Z' as c :: str) -> words (c :: str) Start [] (chunk :: acc)
| InsideAbrev, ('A'..'Z' as a :: ('A'..'Z' as b) :: str) -> words (b :: str) InsideAbrev (a :: chunk) acc
| InsideAbrev, ('A'..'Z' :: 'a'..'z' :: _) -> words str Start [] (chunk :: acc)
| InsideAbrev, ['A'..'Z' as c] -> (c :: chunk) :: acc
| (InsideCamel | InsideAbrev | Start), [] -> chunk :: acc
| _ -> acc
let words input =
let f x = x |> String.to_seq |> List.of_seq in
words (f input) Start [] []
|> List.map (fun cs -> cs |> List.rev |> List.to_seq |> String.of_seq)
|> List.rev
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment