【发布时间】:2019-03-21 05:32:12
【问题描述】:
只是为了好玩,我阅读了these 面试问题并试图在 C# 和 F# 中找到解决方案,但我很难在不改变布尔值或使用正则表达式的情况下遵循惯用的 F#:
给定一个包含一个或多个 $ 符号的字符串,例如: “富吧富$吧$富吧$” 问题:如何从给定字符串中删除第二次和第三次出现的 $?
我的带有突变的命令式 F# 解决方案:
let input = "foo bar foo $ bar $ foo bar $ "
let sb = new StringBuilder()
let mutable first = true
let f c=
if c='$' && first then first<-false
else sb.Append(c) |> ignore
input |> Seq.iter f
(还有一个 C#):
var input = "foo bar foo $ bar $ foo bar $ ";
var sb = new StringBuilder();
bool first = true;
input.ForEach(c => {
switch (c)
{
case '$' when first: first = false; break;
default: sb.Append(c);break;
};
});
【问题讨论】:
标签: .net f# functional-programming c#-to-f# mutation