Page 1 of 1

How to set a local 'Contexts Hash'

Posted: Tue Nov 04, 2014 6:48 am
by ssqq
When default functor used as a pseudo hash function, How to set a local 'Hash'? Because Context is global.

Code: Select all

(define (check-key x)
    ;; I don't know whether environment have defined this symbol
    (define aHash:aHash)
    (aHash 'key-1 1)
    (aHash 'key-2 2)
    (if (aHash x) true nil))

Re: How to set a local 'Contexts Hash'

Posted: Tue Nov 04, 2014 7:59 am
by Lutz
Instead of (define hash:hash) use (new Tree 'hash) it does the same but also makes the default functor hash:hash a constant (containing nil)

Code: Select all

(context 'Foo)

(new Tree 'MAIN:hash) ; must qualify with MAIN, symbol trees are global

(hash "one" 1)
(hash "two" 2)

(println (hash "one")) ; prints 1

(context MAIN)

(println (hash)) ; hash is global
But as a matter of good style, I would pre-define all hashes and pre-create other contexts in a MAIN context module like all other globally used symbols. In bigger newLISP projects or when working with different programmers on the same project clashes/problems are avoided this way.

Re: How to set a local 'Contexts Hash'

Posted: Wed Nov 05, 2014 6:56 am
by ssqq
In bigger project, Context as hash in function maybe pollute global symbol tree.

Code: Select all

(define (make-local-hash)
  (let (local-hash (new Tree 'a-hash))
    (a-hash "one" 1)
    (a-hash "two" 2)
))

(set 'a-hash 2)
(println a-hash) ; => 2
(make-local-hash)
(println a-hash) ; => a-hash

(exit)

Re: How to set a local 'Contexts Hash'

Posted: Wed Nov 05, 2014 7:29 am
by Lutz
We call context dictionaries often "hashes", but there is no hash function at the base of it. "Hash" is just a convenient name as most other languages implement lookup functionality using hash functions.

In newLISP dictionaries are built as separate red-black balanced binary trees and only the root of it - the name of the context - is part of the main symbol space. So no namespace "pollution" is taking place.

Re: How to set a local 'Contexts Hash'

Posted: Wed Nov 26, 2014 11:36 am
by zhanglong
context is value, so we can use (uuid) to generate unique symbol in MAIN, then make it a context. But there's no gc, you have to delete the context yourself.


(set 'a (new Tree (sym (string "_" (uuid)) MAIN)))


delete the context like this

(set 'name (sym (term a) MAIN)) ; find the context's name in MAIN
(delete name) ; delete the context
(delete name) ; delete the symbol in MAIN

Re: How to set a local 'Contexts Hash'

Posted: Thu Jan 08, 2015 2:19 am
by ssqq
thanks, it is a good idea.

Re: How to set a local 'Contexts Hash'

Posted: Thu Mar 24, 2016 4:59 am
by abaddon1234