2
\$\begingroup\$

The purpose of the code is to efficiently stream JSON items from a large file. I am wondering if this is efficient and decently idiomatic. Not sure how I could eliminate the while loop either.

module Seq =
    let inline tryMove (e:IEnumerator<'T>) =
        try
            let moved = e.MoveNext()
            if moved then
                Some <| Choice1Of2 e.Current
            else
                e.Dispose()
                None
        with ex ->
            Some <| Choice2Of2 ex
    let catch (items:_ seq) =
        use e = items.GetEnumerator()
        e
        |> Seq.unfold(
            tryMove
            >> function
            | Some (Choice1Of2 item) -> Some(Choice1Of2 item,e)
            | Some (Choice2Of2 ex) -> Some(Choice2Of2 ex, e)
            | None -> None
        )


module SuperSerial =
    let deserialize<'T>(x):'T =
        JsonConvert.DeserializeObject<'T>(x)

    let streamJson<'T> sr =
        let serializer = JsonSerializer()
        seq{
            use r = new JsonTextReader(sr)
            while r.Read() do
                if r.TokenType = JsonToken.StartObject then
                    yield serializer.Deserialize<'T>(r)
        }
    let streamString<'T> x =
        seq{
            use s = new StringReader(x)
            yield! streamJson(s)
        }
    let streamJsonFile<'T> target =
        seq{
            use s = File.Open(target,FileMode.Open)
            use sr = new StreamReader(s)
            yield! streamJson(sr)
        }
\$\endgroup\$

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Browse other questions tagged or ask your own question.