Skip to content

Instantly share code, notes, and snippets.

@wegry
Created November 16, 2018 09:49
Show Gist options
  • Save wegry/33bd898bfad9b2e6e219e8d67929cd62 to your computer and use it in GitHub Desktop.
Save wegry/33bd898bfad9b2e6e219e8d67929cd62 to your computer and use it in GitHub Desktop.
Write TSV relatively regularly
module Csv
// Transliterated from https://stackoverflow.com/a/4685745/1924257
module private Internals =
let quote = "\""
let escapedQuote = "\\\""
let delimiter = "\t"
let escapedCharacters = ['\t'; '\n'] |> Set.ofList
let escape (s: string) =
let escaped = s.Replace(quote, escapedQuote)
let asSet = escaped.ToCharArray() |> Set.ofSeq
if (Set.intersect asSet escapedCharacters |> Set.isEmpty)
then escaped
else [quote; escaped; quote] |> String.concat ""
let escapeRow (rows: string array) =
rows
|> Seq.map(escape)
|> String.concat delimiter
open Internals
let write (xs: 'a seq) header (transform: 'a -> string array): string =
let processedHeader = escapeRow header
let escapedRows = xs |> Seq.map(transform >> escapeRow) |> List.ofSeq
List.append [ processedHeader ] escapedRows
|> String.concat "\n"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment