Changeset 8731 in project


Ignore:
Timestamp:
02/23/08 23:47:54 (12 years ago)
Author:
mfredrickson
Message:

Hash tables and alists

File:
1 edited

Legend:

Unmodified
Added
Removed
  • wiki/chicken-for-ruby-programmers

    r8729 r8731  
    674674''association lists'' (or ''alists'' for short) or ''hash tables''.
    675675
    676   TODO
     676==== Association Lists
     677
     678Association lists are the simpler Hash like structure in chicken.
     679Effectively, alists are standard lists of ''pairs,'' where the
     680first item in the pair is the key and the second item is the value.
     681Consequently, alists have a nice literal form:
     682
     683  '((foo  1) (bar 42) (baz 101))
     684
     685To lookup a value in the alist, use {{assoc}}. For example to check
     686if the pair {{(bar 42)}} is in the alist:
     687
     688  #;1> (assoc 'bar '((foo  1) (bar 42) (baz 101)))
     689  (bar 42)
     690
     691If the pair is not in the list, you would get the boolean false ({{#f}}).
     692If you need more stringent checks, you can also use {{assq}} or {{assv}},
     693learning more about these procedures is an exercise for the reader.
     694
     695Alists may simplistic, and inquisitive readers may notice that lookup is
     696{{O(n)}} time. However, they are convenient and adding new items is a constant
     697time operation. You may find they work in may places that you might use a
     698small Hash in Ruby.
     699
     700==== Hash tables
     701
     702For more complex hashing operations, Chicken supplies true hash tables.
     703
     704  #;11> (define h (make-hash-table))
     705  #;12> h
     706  #<hash-table>
     707  #;13> (hash-table-set! h 'foo 12)
     708  12
     709  #;14> (hash-table-set! h 'bar 101)
     710  101
     711  #;15> (hash-table-ref h 'bar)
     712  101
     713  #;16> (hash-table-delete! h 'bar)
     714  #t
     715  #;17> (hash-table-ref h 'bar)
     716  Error: (hash-table-ref) hash-table does not contain key
     717  bar
     718
     719Hash tables are more powerful overall, but do not offer convenient literal
     720notation. If you need to convert from a hash table an alist you can use
     721{{hash-table->alist}}. The {{alist->hash-table}} procedure converts in the
     722opposite direction.
     723
    677724== Examples
    678725
Note: See TracChangeset for help on using the changeset viewer.