Created
November 16, 2018 09:49
-
-
Save wegry/33bd898bfad9b2e6e219e8d67929cd62 to your computer and use it in GitHub Desktop.
Write TSV relatively regularly
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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