Hi Factor List,

I'm new to factor, and am in the 'kicking the tyres' stage.

Using a stack language is so different to anything else I'm used to 
(scheme, python, C) that I've been struggling to grok the idiomatic ways 
of doing things. I was hoping that somebody might be able to comment on 
some code to point me in the right directions.

I'm writing a tool to index data. For this I need a mechanism to 
generate sequential IDs for strings seen in the input data. It must 
remember old strings and return their IDs, or generate a new ID if not 
seen before.

After a few goes I came up with the code below, so I'm wondering:

- am I overusing variables to store state where I could be using the stack?
- are there any obvious features I'm missing that makes this easier?

(i.e. basically is there a cleaner way to solve the problem in factor?)

Any hints and pointers would be appreciated since I'm trying to work out 
if factor may be a better general-purpose language than scheme for my needs.

Many thanks,

Phil




unittests
---------

(The public interface is with-idmap and str>id)

[ 0 ]
[ [ "hello" str>id ] with-idmap ] unit-test

[ 0 1 2 1 0 ]
[ [ { "s0" "s1" "s2" "s1" "s0" } [ str>id ] each ] with-idmap ] unit-test


implementation
--------------


<PRIVATE

SYMBOL: current-id
SYMBOL: ids-hash

: set-id ( id string -- )
   ids-hash get set-at ;

: get-id ( string -- id/f )
   ids-hash get at ;

: new-id ( -- id )
   current-id dup inc get ;

: str>new-id ( string -- id )
   new-id dup rot set-id ;

PRIVATE>

: with-idmap ( quotation -- )
   [ H{ } clone ids-hash set
     -1 current-id set
     call ] with-scope ;

: str>id ( string -- id )
   dup get-id [ swap drop ] [ str>new-id ] if* ;


-------------------------------------------------------------------------
This SF.net email is sponsored by: Microsoft
Defy all challenges. Microsoft(R) Visual Studio 2005.
http://clk.atdmt.com/MRT/go/vse0120000070mrt/direct/01/
_______________________________________________
Factor-talk mailing list
[email protected]
https://lists.sourceforge.net/lists/listinfo/factor-talk

Reply via email to