我正在玩 F#语法。
在瑞典,我们有一款名为“Backslang”的游戏(googletranslated from“Rövarspråk”) 规则很简单。你说的所有话都必须以特定的方式说出来。虽然人声是相同的,但每个辅音必须用“o”发音,然后再用辅音发声。
即。 “L”将“LOL”,“星期五”将是 “FOFRORIDODAY”和“BALL”将“BOBALOLLOL”。
我编写了一些看起来非常愚蠢的代码,但却发挥了作用。
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”
为了便于阅读,有没有办法让这段代码更好看?
我是F#和功能编程的新手,所以热烈欢迎任何建议,说明和指示!
答案 0 :(得分:7)
也许是这样的:
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
请注意;这样做的好处是不会创建大量临时string
个对象。
另一种选择是:
let lollify s =
s
|> Seq.map (fun c -> if isVowel c then [|c|] else [|c;'o';c|])
|> Seq.collect id
|> Seq.toArray
|> System.String
答案 1 :(得分:2)
self[:attribute]=value
String.collect
将函数应用于字符串的每个字符。