Page 1 of 1

Searching elements in an association list...

Posted: Thu Dec 01, 2005 12:16 am
by Sunburned Surveyor
I would like to know if there is a function in NewLISP that will return all the elements of an association list based on the value of any of the lists members.

For example, I have the following list:

("fruit" "bannana" "pear" "apple" "plum" "grapes")
("vegatables" "lettuce" "celery" "cucumbers" "olives" "onions")
("junk food" "ice cream" "licorice" "chocolate bar" "carmel apple" "bubble gum")

I want to be able to retrieve the entire "junkfood" list by searching for any one of the elements. I believe the lookup and assoc functions only allow you to do this when using the first element in the association list.

Thanks for the help.

The Sunburned Surveyor

Posted: Thu Dec 01, 2005 2:01 am
by Sammo

Code: Select all

(set 'food-lists
'(
  ("fruit" "bannana" "pear" "apple" "plum" "grapes") 
  ("vegatables" "lettuce" "celery" "cucumbers" "olives" "onions") 
  ("junk food" "ice cream" "licorice" "chocolate bar" "carmel apple" "bubble gum") 
))

(define (magoo findme a-list)
  (a-list ((ref findme a-list) 0)) )
Then

> (magoo "chocolate bar" food-lists)
("junk food" "ice cream" "licorice" "chocolate bar" "carmel apple" "bubble gum")

Posted: Sun Dec 04, 2005 10:09 pm
by Sammo
Improved so that (magoo "no such food" food-lists) returns nil.

Code: Select all

(define (magoo key aList)
  (let
    ( vec (ref key aList) )
  ;body of let
    (and vec (aList (vec 0)) ) ))
> (magoo "no such food" food-lists)
nil
> (magoo "celery" food-lists)
("vegatables" "lettuce" "celery" "cucumbers" "olives" "onions")