utils.rkt 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. #lang racket
  2. (provide get-lines
  3. enumerate
  4. repeat
  5. split-list-by)
  6. (define (repeat n e)
  7. (let loop ((i 0) (ret '()))
  8. (if (>= i n)
  9. ret
  10. (loop (+ 1 i) (cons e ret)))))
  11. (define (trim-lines lines)
  12. (if (= 0 (string-length (car lines)))
  13. (trim-lines (cdr lines))
  14. lines))
  15. (define (get-lines fp)
  16. (define lines
  17. (let loop ((lines '()))
  18. (define l (read-line fp))
  19. (if (eof-object? l)
  20. (reverse lines)
  21. (loop (cons l lines)))))
  22. (reverse (trim-lines (reverse (trim-lines lines)))))
  23. (define (enumerate lst)
  24. (let loop ((i 1) (ret '()) (remain lst))
  25. (if (null? remain)
  26. (reverse ret)
  27. (loop (+ 1 i) (cons (list (car remain) i) ret) (cdr remain)))))
  28. (define (split-list-by e lst . eq)
  29. (define cmp (if (null? eq) equal? eq))
  30. (let loop ((ret '())
  31. (cur '())
  32. (lst lst))
  33. (if (null? lst)
  34. (reverse (cons (reverse cur) ret))
  35. (if (cmp e (car lst))
  36. (loop (cons (reverse cur) ret) '() (cdr lst))
  37. (loop ret (cons (car lst) cur) (cdr lst))))))