gpt4 book ai didi

replace - F#:替换为 .Replace ("oldValue","newValue")

转载 作者:行者123 更新时间:2023-12-04 22:58:13 30 4
gpt4 key购买 nike

我在玩 F# 句法。

在瑞典,我们有一个游戏叫做“Backslang”(谷歌翻译自“Rövarspråk”)
规则很简单。你说的所有话都必须以特定的方式说出来。虽然人声是相同的,但每个辅音都必须用“o”发音,然后是辅音。

I.e. "L" would be "LOL", "FRIDAY" would be "FOFRORIDODAY" and "BALL" would be "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# 和函数式编程的新手,因此热烈欢迎任何建议、技巧和指针!

最佳答案

也许是这样的:

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

关于replace - F#:替换为 .Replace ("oldValue","newValue"),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35206010/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com