折叠数组数组

时间:2014-11-07 09:41:30

标签: arrays f# concatenation

我试图将一串字符串数组折叠成一个字符串,但我没有太多运气。不幸的是,似乎Array.reduce期望我的lambda返回一个字符串数组,因为它是一个字符串数组的数组。

我得到了:

  

行错误37:类型'字符串[]'与类型'字符串'

不匹配

这是违规行

(fold state) + (fold item)

因为它期望lambda返回string[]

以下是代码:

let splitStr (seperator: string[]) (str: string) = str.Split(seperator, StringSplitOptions.None)
let convertFile fileName =
    let arrayToTransaction arr =
        let rec foldArray index (sb: StringBuilder) (arr:string[]) =
            if index > 5 then sb.ToString()
            else 
                let text = 
                    match index with
                    | 0 -> sb.Append(DateTime.Parse(arr.[1]).ToString("dd/MM/yy", CultureInfo.InvariantCulture))
                    | 1 -> sb.Append(arr.[0].Substring(0, arr.[0].IndexOf(',')).Trim())
                    | 2 -> sb.Append("Test")
                    | 3 -> sb.Append("Test")
                    | 4 -> sb.Append(Single.Parse(arr.[2].Substring(arr.[2].IndexOf('-') + 1)).ToString("F2", CultureInfo.InvariantCulture))
                    | _ -> sb.Append(String.Empty)
                foldArray (index + 1) (text.Append(",")) arr

        arr 
        |> Array.map (splitStr [|"\n"|])
        |> Array.reduce (fun state item -> let fold x = foldArray 0 (new StringBuilder()) x
                                           (fold state) + (fold item))

    File.ReadAllText(fileName)
    |> splitStr [|"\r\n\r\n"|]
    |> arrayToTransaction

1 个答案:

答案 0 :(得分:2)

Array.reduce中的lambda必须返回string[],因为lambda的签名是'T->'T->'T,而第一个'T已经统一为string[]所以结果也应该是string[]