rewrite macros for updating association-lists

Q&A's, tips, howto's
Locked
William James
Posts: 58
Joined: Sat Jun 10, 2006 5:34 am

rewrite macros for updating association-lists

Post by William James »

Code: Select all

(macro (assoc-push Alist Key Val)
  (let (key Key  val Val)
    (or
      (catch
        (push val (or (lookup key Alist) (throw nil)) -1))
      (push (list key (list val)) Alist -1))))

(macro (assoc++ Alist Key Val)
  (let (key Key  val Val)
    (or
      (catch
        (++ (or (lookup key Alist) (throw nil)) (or val 1)))
      (push (list key (or val 1)) Alist -1))))
Example:

Code: Select all

(define (word-counts wlist)
  (let (counts '())
    (dolist (word wlist)  (assoc++ counts word))
    counts))

(word-counts (find-all "[a-z]+" (lower-case 
  {"The time has come," the Walrus said,
  "To talk of many things:
  Of shoes--and ships--and sealing-wax--
  Of cabbages--and kings--
  And why the sea is boiling hot--
  And whether pigs have wings."})))

(("the" 3) ("time" 1) ("has" 1) ("come" 1) ("walrus" 1) ("said" 1)
 ("to" 1) ("talk" 1) ("of" 3) ("many" 1) ("things" 1) ("shoes" 1)
 ("and" 5) ("ships" 1) ("sealing" 1) ("wax" 1) ("cabbages" 1)
 ("kings" 1) ("why" 1) ("sea" 1) ("is" 1) ("boiling" 1) ("hot" 1)
 ("whether" 1) ("pigs" 1) ("have" 1) ("wings" 1))

Lutz
Posts: 5289
Joined: Thu Sep 26, 2002 4:45 pm
Location: Pasadena, California
Contact:

Re: rewrite macros for updating association-lists

Post by Lutz »

one can use the function bayes-train for counting words:

Code: Select all

(set 'text {"The time has come," the Walrus said,
  "To talk of many things:
  Of shoes--and ships--and sealing-wax--
  Of cabbages--and kings--
  And why the sea is boiling hot--
  And whether pigs have wings."})

(bayes-train (find-all "[a-z]+" (lower-case text)) 'Words)

(map flat (Words))  =>

    (("and" 5) ("boiling" 1) ("cabbages" 1) ("come" 1) ("has" 1)
    ("have" 1) ("hot" 1) ("is" 1) ("kings" 1) ("many" 1) ("of" 3)
    ("pigs" 1) ("said" 1) ("sea" 1) ("sealing" 1) ("ships" 1)
    ("shoes" 1) ("talk" 1) ("the" 3) ("things" 1) ("time" 1) ("to" 1)
    ("walrus" 1) ("wax" 1) ("whether" 1) ("why" 1) ("wings" 1))
see here: http://www.newlisp.org/downloads/newlis ... ayes-train
and here: http://www.newlisp.org/downloads/newlis ... ayes-query

Locked