Autoincrement keys for hash tree

Q&A's, tips, howto's
Locked
hilti
Posts: 140
Joined: Sun Apr 19, 2009 10:09 pm
Location: Hannover, Germany
Contact:

Autoincrement keys for hash tree

Post by hilti »

Hi!

I'm stucked in generating auto increment keys for a hash tree. Here's my approach:

Code: Select all

(new Tree 'products)

(define (highest-key tree)
	(if-not (empty? (tree))
		(begin
			(println "Tree is not empty.")
			(string (inc (integer (first (last (sort (tree)) <)))))
		)
		(begin
			(println "Tree is empty.")
			(string (integer 1))
		)
	)
)

(products (highest-key products) "hello")
(products (highest-key products) "hello")
(products (highest-key products) "hello")
(products (highest-key products) "hello")
(products (highest-key products) "hello")
(products (highest-key products) "hello")
(products (highest-key products) "hello")
(products (highest-key products) "hello")
(products (highest-key products) "hello")
(products (highest-key products) "hello")
(products (highest-key products) "hello")
(products (highest-key products) "hello")

(products)
The thing is: hash keys have to be strings, right? And that's why I get in troubles on sorting this list, which (products) returns.

Code: Select all

(("1" "hello") ("10" "hello") ("2" "hello") ("3" "hello") ("4" "hello") ("5" "hello") 
 ("6" "hello") 
 ("7" "hello") 
 ("8" "hello") 
 ("9" "hello"))
Is there another approach for hash keys? What are You guys using?

Cheers
Hilti
--()o Dragonfly web framework for newLISP
http://dragonfly.apptruck.de

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

Re: Autoincrement keys for hash tree

Post by Lutz »

Code: Select all

> (new Tree 'Hash)
Hash
> (Hash (format "%05d" (inc Hash:counter)) "A")
"A"
> (Hash (format "%05d" (inc Hash:counter)) "B")
"B"
> (Hash)
(("00001" "A") ("00002" "B"))
> (symbols Hash)
(Hash:Hash Hash:_00001 Hash:_00002 Hash:counter)
>
The variable 'Hash:counter' is automatically created when newLISP reads the statement and 'inc' brings it from 'nil' to 0. The format makes sure that the sort order is Ok.

hilti
Posts: 140
Joined: Sun Apr 19, 2009 10:09 pm
Location: Hannover, Germany
Contact:

Re: Autoincrement keys for hash tree

Post by hilti »

Thanks Lutz! Your solution works great. I think this is a cool snippet for the Code Patterns documentation.
--()o Dragonfly web framework for newLISP
http://dragonfly.apptruck.de

Locked