rebellion icon indicating copy to clipboard operation
rebellion copied to clipboard

More featureful `hash-copy` in rebellion/collection/hash

Open samdphillips opened this issue 5 years ago • 2 comments

The Racket hash-copy makes a shallow copy of the hash. Maybe more useful would be a copier that could optionally take a procedures to copy a key and/or a procedure to copy a value. The returned hash should have the same mutability, key comparison, key holding strength as the original.

(hash-copy
  hash?
  #:key-copy   [(Key -> Key) values]
  #:value-copy [(Value -> Value) values]) -> hash?

samdphillips avatar Dec 10 '19 04:12 samdphillips

My first instinct would be to reach for transduce, in-hash-entries, and a reducer for whichever type of hash I was copying. Would that work for your use case?

jackfirth avatar Dec 10 '19 07:12 jackfirth

Yes. Having the tools available in Rebellion is convenient (and probably a good path for implementation.)

Thinking this over more I have a few observations (which may be obvious, but whatever):

  • this kind of copying operation is really only needed when you have a data structure that has a mutable subpart.
  • there could be a general API pattern over "containers"
    • ($thing-copy a-$thing copy-part ...)
      • (hash-copy a-hash key-copy value-copy)
      • (vector-copy a-vector value-copy)
      • (list-copy a-list value-copy)
      • etc ...
  • I think for linear types (like hash, vector, list, mlist) all of the implementations can use a core generic copier (untested off the top of my head):
(define (make-type-copier type->sequence type-reducer)
  (lambda (orig-value copy-element)
    (transducer 
      (type->sequence orig-value)
      (mapping copy-element)
      #:into type-reducer)))

samdphillips avatar Dec 10 '19 22:12 samdphillips