Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
A simple CSV file
type Csv private(headers : string[], data : string [] []) =
let headers = ResizeArray<string>(headers)
let data = ResizeArray(data |> Array.map (ResizeArray))
static member Empty = Csv([||], [||])
static member Read(file:string) =
let csv = CsvFile.Load(file)
let headers =
match csv.Headers with
| Some hs -> hs
| None -> failwithf "The csv file must have headers"
new Csv(headers, [| for header in headers do yield [|for row in csv.Rows -> row.GetColumn(header)|] |])
member x.GetValue(col, indx) =
match data |> Seq.tryItem indx with
| Some row ->
headers
|> Seq.tryFindIndex ((=) col)
|> Option.bind (fun colIndx -> row |> Seq.tryItem colIndx)
| None -> None
member x.SetValue(col, indx, value) =
match data |> Seq.tryItem indx with
| Some row ->
match headers |> Seq.tryFindIndex ((=) col) with
| Some colIndex ->
row.Insert(colIndex, value)
| None ->
headers.Add(col)
row.Insert(headers.Count - 1, value)
| None ->
let row = ResizeArray<_>()
match headers |> Seq.tryFindIndex ((=) col) with
| Some colIndex ->
row.Insert(colIndex, value)
| None ->
headers.Add(col)
row.Insert(headers.Count - 1, value)
data.Insert(indx, row)
member x.Data
with get() =
[|
yield headers |> Seq.toArray
for row in data do
yield [| for value in row -> value |]
|]
override x.ToString() =
let sb = new Text.StringBuilder()
for row in x.Data do
sb.AppendLine(String.concat "," row) |> ignore
sb.ToString()
member x.Save(path) =
IO.File.WriteAllText(path, x.ToString())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment