-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathCsv.scala
More file actions
60 lines (53 loc) · 1.81 KB
/
Copy pathCsv.scala
File metadata and controls
60 lines (53 loc) · 1.81 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package alpaca
package internal
import scala.NamedTuple.NamedTuple
/**
* Represents data in CSV (Comma-Separated Values) format.
*
* This case class holds tabular data with headers and rows that can be
* displayed as a CSV string. It is used internally for debug output.
*
* Note: Future improvements may include making this Tuple-based for
* better type safety and performance.
*
* @param headers the column headers
* @param rows the data rows, each containing values for each column
*/
//todo: make Tuple-based in the future for better type safety and performance
private[internal] final case class Csv(
headers: List[Shown],
rows: List[List[Shown]],
)
private[internal] object Csv:
/**
* Showable instance for Csv that formats it as a comma-separated value string.
*
* The output has headers on the first line followed by data rows,
* with values separated by commas.
*/
given Showable[Csv] = Showable: csv =>
val header = csv.headers.mkShow(",")
val rows = csv.rows.map(_.mkShow(",")).mkShow("\n")
show"$header\n$rows"
extension [N <: Tuple, V <: Tuple](rows: List[NamedTuple[N, V]])
/**
* Converts a list of named tuples to CSV format.
*
* The tuple field names become the CSV headers, and the values
* become the data rows. This is useful for exporting structured
* data to CSV.
*
* @return a Csv representation of the named tuples
*/
inline def toCsv(using DebugSettings): Csv =
Csv(
compiletime.constValueTuple[N].toShowableList,
rows.map(_.toTuple.toShowableList),
)
extension [T <: Tuple](tuple: T)
inline private def toShowableList(using DebugSettings) = compiletime
.summonAll[Tuple.Map[T, Showable]]
.zip(tuple)
.toList
.asInstanceOf[List[(Showable[Any], Any)]]
.map(_.show(_))