utils.rkt 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. #lang racket
  2. (provide get-lines
  3. enumerate
  4. repeat
  5. split-list-by
  6. transpose-list)
  7. (define (repeat n e)
  8. (let loop ((i 0) (ret '()))
  9. (if (>= i n)
  10. ret
  11. (loop (+ 1 i) (cons e ret)))))
  12. (define (trim-lines lines)
  13. (if (= 0 (string-length (car lines)))
  14. (trim-lines (cdr lines))
  15. lines))
  16. (define (get-lines fp)
  17. (define lines
  18. (let loop ((lines '()))
  19. (define l (read-line fp))
  20. (if (eof-object? l)
  21. (reverse lines)
  22. (loop (cons l lines)))))
  23. (reverse (trim-lines (reverse (trim-lines lines)))))
  24. (define (enumerate lst)
  25. (let loop ((i 1) (ret '()) (remain lst))
  26. (if (null? remain)
  27. (reverse ret)
  28. (loop (+ 1 i) (cons (list (car remain) i) ret) (cdr remain)))))
  29. (define (split-list-by e lst . eq)
  30. (define cmp (if (null? eq) equal? eq))
  31. (let loop ((ret '())
  32. (cur '())
  33. (lst lst))
  34. (if (null? lst)
  35. (reverse (cons (reverse cur) ret))
  36. (if (cmp e (car lst))
  37. (loop (cons (reverse cur) ret) '() (cdr lst))
  38. (loop ret (cons (car lst) cur) (cdr lst))))))
  39. (define (transpose-list lines)
  40. (define width (string-length (car lines)))
  41. (define new-lines (make-vector width))
  42. (let loop ((i 0))
  43. (if (>= i width)
  44. (vector->list new-lines)
  45. (let ()
  46. (define char-list (map (λ (l) (string-ref l i)) lines))
  47. (vector-set! new-lines i (list->string char-list))
  48. (loop (+ i 1))))))