如何在F#中遍历String [] [] [英] How to traverse String[][] in F#

查看:83
本文介绍了如何在F#中遍历String [] []的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

上下文:Microsoft Visual Studio 2015社区; F#

Context: Microsoft Visual Studio 2015 Community; F#

我每天学习F#大约1/2.我对使用 mLite 花了一年的时间来做函数编程还是有一个模糊的想法.

I've been learning F# for about 1/2 a day. I do have a vague idea of how to do functional programming from a year spent fiddling with mLite.

以下脚本遍历文件夹树并提取日志文件.这些文件具有以~分隔的条目,并且那里可能有一个或多个.

The following script traverses a folder tree and pulls in log files. The files have entries delimited by ~ and there may be one or more there.

open System
open System.IO

let files = 
    System.IO.Directory.GetFiles("C:\\scratch\\snapshots\\", "*.log", SearchOption.AllDirectories)

let readFile (file: string) = 
    //Console.WriteLine(file)
    let text = File.ReadAllText(file) 
    text

let dataLines (line: string) = 
    line.Split('~')

let data = 
    files |> Array.map readFile |> Array.map dataLines

因此,在这一点上,data包含一个String[][],我不知所措,想出如何将其转换为String[]的想法是我想将所有日志都转换为一个长向量,以便我可以对其进行一些其他转换.例如,每条日志行都以日期时间开头,因此将其全部变成一个长列表,然后我就可以对日期时间进行排序.

So at this point data contains a String[][] and I'm at a bit of a loss to figure out how to turn it into a String[], the idea being that I want to convert all the logs into one long vector so that I can do some other transformations on it. For example, each log line begins with a datetime so having turned it all into one long list I can then sort on the datetime.

从这里到哪里?

推荐答案

如注释中所述,您可以使用Array.concat:

As stated in the comments, you can use Array.concat :

files |> Array.map readFile |> Array.map dataLines |> Array.concat

现在进行一些重构,两个映射的组成等同于两个函数的映射.

Now some refactoring, the composition of two maps is equivalent to the map of the composition of both functions.

files |> Array.map (readFile >> dataLines) |> Array.concat

最后,map >> concat等同于collect.因此,您的代码将变为:

Finally map >> concat is equivalent to collect. So your code becomes:

files |> Array.collect (readFile >> dataLines)

这篇关于如何在F#中遍历String [] []的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆