alist-procs.scm 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. (library (lib alist-procs)
  2. (export alist-key-not-found-error-message
  3. alist-ref
  4. alist-nested-refs)
  5. (import (except (rnrs base) let-values map error)
  6. (only (guile)
  7. lambda* λ
  8. current-output-port
  9. call-with-output-string
  10. simple-format
  11. error)
  12. ;; alist procs
  13. (srfi srfi-1)
  14. ;; hash-tablesx
  15. (srfi srfi-69)))
  16. (define alist-key-not-found-error-message
  17. (λ (alst key)
  18. (call-with-output-string
  19. (λ (string-port)
  20. (simple-format string-port
  21. "could not find key ~s in alist ~a\n"
  22. key
  23. alst)))))
  24. (define alist-ref
  25. (lambda* (alst
  26. key
  27. #:key
  28. (equality-test equal?)
  29. (default (λ ()
  30. (error
  31. (alist-key-not-found-error-message alst key)))))
  32. ;; (simple-format (current-output-port) "alist: ~a\n" alst)
  33. (cond
  34. [(null? alst) (default)]
  35. [else
  36. (let ([current (first alst)])
  37. (cond
  38. [(equality-test (first current) key)
  39. (cdr current)]
  40. [else
  41. (alist-ref (cdr alst)
  42. key
  43. #:equality-test equality-test
  44. #:default default)]))])))
  45. (define alist-nested-refs
  46. (lambda* (alst
  47. keys
  48. #:key
  49. (equality-test equal?)
  50. (default (λ ()
  51. (error
  52. (alist-key-not-found-error-message alst keys)))))
  53. (cond
  54. [(null? alst) (default)]
  55. [(null? keys) alst]
  56. [else
  57. (let ([current (first alst)] [key (first keys)])
  58. (cond
  59. [(equality-test (first current) key)
  60. (alist-nested-refs (cdr current)
  61. (cdr keys)
  62. #:equality-test equality-test
  63. #:default default)]
  64. [else
  65. (alist-nested-refs (cdr alst)
  66. keys
  67. #:equality-test equality-test
  68. #:default default)]))])))
  69. ;; (define first-elem-assoc?
  70. ;; (λ (sth)
  71. ;; (or (null? sth)
  72. ;; (and
  73. ;; ;; (not-null? sth)
  74. ;; (pair? sth)
  75. ;; (pair? (first sth))
  76. ;; (not (proper-list? (first sth)))))))
  77. ;; (define alist->hash-table*
  78. ;; (λ (alst)
  79. ;; (cond
  80. ;; []
  81. ;; [])))