F# - 按间隔将列表拆分为连续字符串

时间:2009-01-14 01:59:13

标签: .net f# list concatenation fold

我有一个电子邮件地址列表,我需要向每个地址发送电子邮件通知。我想一次在25个地址的块中执行此操作。有没有像F#这样的函数式语言快速“折叠”(连接)25个电子邮件地址......每个地址用分号分隔。我知道.NET中有String.Split方法,但我需要一次连接25个。

在F#中执行此操作的最佳方法是什么?

4 个答案:

答案 0 :(得分:1)

这是一种打破最多N组的方法:

// break a sequence up into a sequence of arrays, 
// each of length at most 'n'
let Break n (s:seq<_>) =
    seq {
        use e = s.GetEnumerator()
        while e.MoveNext() do
            let i = ref 0
            yield [|
                yield e.Current
                i := !i + 1
                while !i < n && e.MoveNext() do            
                    yield e.Current
                    i := !i + 1 |] }

然后你的解决方案就像是

let Sendmail addr = printf "%A\n\n" addr
let allMails = [for i in 1..25 -> sprintf "a%i@example.com" i]
allMails 
|> Break 5
|> Seq.map (fun arr -> System.String.Join(";", arr))
|> Seq.iter Sendmail

答案 1 :(得分:1)

如果这仍然相关,这里是一个使用分隔符连接字符串序列但不转换为数组的函数。

open System
open System.Text

/// Join a sequence of strings using a delimiter.
/// Equivalent to String.Join() but without arrays.
let join (items : seq<string>) (delim : string) =
    // Collect the result in the string builder buffer
    // The end-sequence will be "item1,delim,...itemN,delim"
    let buff = 
        Seq.fold 
            (fun (buff :StringBuilder) (s:string) -> buff.Append(s).Append(delim)) 
            (new StringBuilder()) 
            items

    // We don't want the last delim in the result buffer, remove
    buff.Remove(buff.Length-delim.Length, delim.Length).ToString()

答案 2 :(得分:0)

它并不过分漂亮,但它有效:

let breakWords separator groupSize (input : string) =
    let words = input.Split([| separator |])
    let arraySize = words.Length / groupSize + (if words.Length % groupSize > 0 then 1 else 0)
    let groups = Array.init arraySize (fun index ->
        let startIndex = index * groupSize
        let endIndex = Math.Min(startIndex + groupSize - 1, words.Length - 1)
        words.[startIndex .. endIndex])
    groups |> Seq.map (fun x -> String.Join(";", x))

答案 3 :(得分:0)

Seq模块有一个窗口函数,但是它会给你一个滑动窗口,所以对这个问题没什么好处。

这是我的版本,我没有测试过性能与其他答案的比较,但它更漂亮(我想!)

//Add an "extension function" to the Seq module
module Seq = 
    let rec chunks n (s:#seq<_>) =
        seq {
                 if Seq.length s <= n then
                    yield s
                 else
                    yield Seq.take n s
                    yield! chunks n (Seq.skip n s)           
            }

//Make curried version of String.Join
let join sep (s:#seq<string>) = System.String.Join(sep, Array.of_seq s)

//Compose the bits together
let mailMerge n = Seq.chunks n >> Seq.map (join ";")

//Test
mailList |> mailMerge 25

您也可以查看Array slices