Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

F#: Substitute to .Replace("oldValue","newValue")

I'm playing around a little with F# syntax.

In Sweden we have a game called "Backslang" (googletranslated from "Rövarspråk") The rules are quite simple. All words you say must be said in a specific way. While vocals are the same, each consonant must be pronounced with an "o" followed by the consonant again.

I.e. "L" would be "LOL", "FRIDAY" would be "FOFRORIDODAY" and "BALL" would be "BOBALOLLOL".

I wrote some code that looks really stupid but does its job.

let myWord (x:string) = 
    x.Replace("q","qoq").Replace("w","wow").Replace("r","ror").Replace("t","tot").Replace("p","pop").Replace("s","sos").Replace("d","dod").Replace("f","fof").Replace("g","gog").Replace("h","hoh").Replace("j","joj").Replace("k","kok").Replace("l","lol").Replace("z","zoz").Replace("x","xox").Replace("c","coc").Replace("v","vov").Replace("b","bob").Replace("n","non").Replace("m","mom").Replace("Q","QOQ").Replace("W","WOW").Replace("R","ROR").Replace("T","TOT").Replace("P","POP").Replace("S","SOS").Replace("D","DOD").Replace("F","FOF").Replace("G","GOG").Replace("H","HOH").Replace("J","JOJ").Replace("K","KOK").Replace("L","LOL").Replace("Z","ZOZ").Replace("X","XOX").Replace("C","COC").Replace("V","VOV").Replace("B","Bob").Replace("N","Non").Replace("M","Mom").ToLower()   

    myWord "ball"

F# Interactive: val it : string = "bobalollol"

For the sake of readability, is there any way to give this code a better look?

I'm a newbie to F# and Functional Programming so any advices, protips and pointers are warmly welcome!

like image 731
Awots Avatar asked Jan 07 '23 17:01

Awots


2 Answers

Perhaps something like this:

let isVowel = function
  | 'a' | 'e' | 'i' | 'o' | 'u' | 'y' | 'å' | 'ä' | 'ö'
  | 'A' | 'E' | 'I' | 'O' | 'U' | 'Y' | 'Å' | 'Ä' | 'Ö' -> true
  | _ -> false

let lollify s =
  [| for c in s do if isVowel c then yield c else yield c; yield 'o';yield c |]
  |> System.String

[<EntryPoint>]
let main argv = 
  printfn "%A" <| lollify "Ball"
  0

Note; this also has the benefit of not creating alot of temporary string objects.

Another option would be this:

let lollify s =
  s
  |> Seq.map (fun c -> if isVowel c then [|c|] else [|c;'o';c|])
  |> Seq.collect id
  |> Seq.toArray
  |> System.String
like image 139
Just another metaprogrammer Avatar answered Jan 18 '23 01:01

Just another metaprogrammer


String.collect (string >> function
    | vowel when "aeiouyåäöAEIOUYÅÄÖ".Contains vowel -> vowel
    | consonant -> consonant + "o" + consonant )

String.collect applies a function to each char of a string.

like image 34
kaefer Avatar answered Jan 18 '23 01:01

kaefer