CSV
Parse and generate CSV (Comma-Separated Values) data. Supports custom delimiters, header rows, and proper escaping of special characters.
import Encoding.CSV
Parsing
CSV.parse
String -> [[String]]
Parse a CSV string into a list of rows, where each row is a list of fields.
csv = "name,age,city\nAlice,30,NYC\nBob,25,LA"
rows = CSV.parse csv
# [["name", "age", "city"], ["Alice", "30", "NYC"], ["Bob", "25", "LA"]]
CSV.parse-headers
String -> [a]
Parse CSV with the first row as headers. Returns a list of records where
each record has fields named after the headers.
csv = "name,age\nAlice,30\nBob,25"
records = CSV.parse-headers csv
# [{name: "Alice", age: "30"}, {name: "Bob", age: "25"}]
CSV.parse-row
String -> [String]
Parse a single CSV row into a list of fields.
row = CSV.parse-row "Alice,30,NYC"
# ["Alice", "30", "NYC"]
Custom Delimiters
All parsing functions have -with variants that accept a custom delimiter.
Useful for TSV (tab-separated), pipe-separated, or other formats.
CSV.parse-with
String -> String -> [[String]]
Parse with a custom delimiter character.
# Parse tab-separated values
tsv = "name\tage\nAlice\t30"
rows = CSV.parse-with "\t" tsv
# Parse pipe-separated values
psv = "name|age\nAlice|30"
rows = CSV.parse-with "|" psv
CSV.parse-headers-with
String -> String -> [a]
Parse with headers using a custom delimiter.
CSV.parse-row-with
String -> String -> [String]
Parse a single row with a custom delimiter.
Formatting
CSV.to-csv
[[String]] -> String
Format rows into a CSV string.
rows = [["name", "age"], ["Alice", "30"]]
csv = CSV.to-csv rows
# "name,age\nAlice,30"
CSV.to-csv-with
String -> [[String]] -> String
Format rows with a custom delimiter.
CSV.row-to-csv
[String] -> String
Format a single row into a CSV line.
CSV.row-to-csv-with
String -> [String] -> String
Format a single row with a custom delimiter.
CSV.escape
String -> String
Escape a field for CSV output. Adds quotes if the field contains
commas, quotes, or newlines.
escaped = CSV.escape "Hello, World"
# "\"Hello, World\""
File I/O
CSV.read
String -> Result [[String]] IOError
Read and parse a CSV file.
match CSV.read "data.csv"
| Ok rows -> process rows
| Err e -> println "Error reading file: ${e}"
CSV.read-with
String -> String -> Result [[String]] IOError
Read a file with a custom delimiter.
CSV.read-headers
String -> Result [a] IOError
Read a CSV file with the first row as headers.
CSV.read-headers-with
String -> String -> Result [a] IOError
Read a file with headers and a custom delimiter.
CSV.write
String -> [[String]] -> Result () IOError
Write rows to a CSV file.
rows = [["name", "age"], ["Alice", "30"]]
match CSV.write "output.csv" rows
| Ok _ -> println "Saved successfully"
| Err e -> println "Error: ${e}"
CSV.write-with
String -> String -> [[String]] -> Result () IOError
Write to a file with a custom delimiter.