Skip to content

Instantly share code, notes, and snippets.

@ReedCopsey
Last active December 22, 2020 15:30
Show Gist options
  • Save ReedCopsey/137e02d6b103c36646330d9bc85da341 to your computer and use it in GitHub Desktop.
Save ReedCopsey/137e02d6b103c36646330d9bc85da341 to your computer and use it in GitHub Desktop.
12/17/2020 1928 Child in snow
12/17/2020 1929 Child grabbing snow
12/17/2020 1930 Snowball being formed
12/17/2020 1931 Snowball flinging towards tree
12/17/2020 1932 Tree gets hit
12/17/2020 1933 Tree vibrates
12/17/2020 1934 Snow falls off branches
12/17/2020 1935 Snow lands on child and dog
12/17/2020 1936 The dog wimpers, then says "Woof"
12/17/2020 1937 The child hugs dog
12/17/2020 1938 Everybody runs around
12/17/2020 1939 A good time is had by all
let getIds (events : Event list) =
let ids = events |> List.map (fun e -> e.ID)
let min = ids |> List.min
let max = ids |> List.max
{ Start = min ; End = max }
let file = openFile "C:\\users\\reedc\\desktop\\events.csv"
let csv = file |> Result.map openCsv
let openCsv (strm : Stream) =
new CsvReader(new StreamReader(strm), Globalization.CultureInfo.InvariantCulture)
let openFile filename =
try
File.OpenRead filename
|> Result.Ok
with
| e ->
IO(message = "Could not open file", exn = e)
|> Result.Error
let readRow (reader : CsvReader) =
if reader.Read () then
let evt = {
Date = reader.GetField<DateTime>(0) ;
ID = reader.GetField<int>(1) ;
Description = reader.GetField<string>(2)
}
Some evt
else None
let readRowsAndClose reader =
try
try
let rows =
Seq.initInfinite (fun _ -> readRow reader)
|> Seq.takeWhile (fun r -> r.IsSome)
|> Seq.choose id
|> Seq.toList
if List.isEmpty rows then
Result.Error DataMissing
else Result.Ok rows
with
| e ->
DataMalformed ("Unable to parse data", e)
|> Result.Error
finally
reader.Dispose ()
let result =
openFile "C:\\users\\reedc\\desktop\\events.csv"
|> Result.map openCsv
|> Result.bind readRowsAndClose
|> Result.map getIds
// The data in our rows
type Event = { Date : DateTime ; ID : int ; Description : string }
// Our end result
type Range = { Start : int ; End : int }
// Our potential problems
type Issue =
| IO of message : string * exn : Exception
| DataMissing
| DataMalformed of message : string * exn : Exception
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment