Eric Lippert's challenge “comma-quibbling”, best answer?

后端 未结 27 2191
日久生厌
日久生厌 2020-12-01 06:59

I wanted to bring this challenge to the attention of the stackoverflow community. The original problem and answers are here. BTW, if you did not follow it before, you should

27条回答
  •  抹茶落季
    2020-12-01 07:24

    Here's a simple F# solution, that only does one forward iteration:

    let CommaQuibble items =
        let sb = System.Text.StringBuilder("{")
        // pp is 2 previous, p is previous
        let pp,p = items |> Seq.fold (fun (pp:string option,p) s -> 
            if pp <> None then
                sb.Append(pp.Value).Append(", ") |> ignore
            (p, Some(s))) (None,None)
        if pp <> None then
            sb.Append(pp.Value).Append(" and ") |> ignore
        if p <> None then
            sb.Append(p.Value) |> ignore
        sb.Append("}").ToString()
    

    (EDIT: Turns out this is very similar to Skeet's.)

    The test code:

    let Test l =
        printfn "%s" (CommaQuibble l)
    
    Test []
    Test ["ABC"]        
    Test ["ABC";"DEF"]        
    Test ["ABC";"DEF";"G"]        
    Test ["ABC";"DEF";"G";"H"]        
    Test ["ABC";null;"G";"H"]        
    

提交回复
热议问题