Changeset 8731 in project

02/23/08 23:47:54 (12 years ago)

Hash tables and alists

1 edited


  • wiki/chicken-for-ruby-programmers

    r8729 r8731  
    674674''association lists'' (or ''alists'' for short) or ''hash tables''.
    676   TODO
     676==== Association Lists
     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:
     683  '((foo  1) (bar 42) (baz 101))
     685To lookup a value in the alist, use {{assoc}}. For example to check
     686if the pair {{(bar 42)}} is in the alist:
     688  #;1> (assoc 'bar '((foo  1) (bar 42) (baz 101)))
     689  (bar 42)
     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.
     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.
     700==== Hash tables
     702For more complex hashing operations, Chicken supplies true hash tables.
     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
     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.
    677724== Examples
Note: See TracChangeset for help on using the changeset viewer.