csv-to-list.rkt 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. #lang racket
  2. (require csv-reading)
  3. (require rackunit)
  4. (provide all-rows
  5. DEFAULT-DATA-READER-MAKER)
  6. ;; the data-reader will be able to understand the specific CSV format
  7. (define DEFAULT-DATA-READER-MAKER
  8. (make-csv-reader-maker
  9. '((seperator-chars #\,)
  10. (strip-leading-whitespace . true)
  11. (strip-trailing-whitespace . true))))
  12. (define (all-rows a-file-path
  13. #:a-reader-maker [a-reader-maker DEFAULT-DATA-READER-MAKER]
  14. #:column-converters [column-converters empty])
  15. (define next-row
  16. (a-reader-maker (open-input-file a-file-path)))
  17. (define (convert-row row column-converters)
  18. (define (col-iter remaining-columns remaining-column-converters)
  19. (cond [(empty? remaining-columns) empty]
  20. [else (cond [(empty? remaining-column-converters)
  21. (cons (first remaining-columns)
  22. (col-iter (rest remaining-columns) empty))]
  23. [else (cons ((first remaining-column-converters) (first remaining-columns))
  24. (col-iter (rest remaining-columns)
  25. (rest remaining-column-converters)))])]))
  26. (col-iter row column-converters))
  27. (define (row-iter)
  28. (let ([row (next-row)])
  29. (cond [(empty? row) empty]
  30. [else (cons (list->vector (convert-row row column-converters))
  31. (row-iter))])))
  32. (row-iter))
  33. #|
  34. ====
  35. USAGE EXAMPLE:
  36. (define data-set (all-rows FILE-PATH))
  37. ====
  38. |#