I just got smarter by a Factor!

February 13th, 2008

I finally took some time to play with Factor. I approached it with some scepticism because after looking at various examples I wasn’t sure if I really want to shuffle the stack instead of use the ( old boring ) variables.

This is an much repeated example of sq (square) word (function) in Factor.

: sq dup * ;

Well, I came with scepticism but left enthusiastic. When I was thinking out cutoff word I thought to myself that factor is cool as a brain exercise, like tetris, but that it's probably more practical to just use something less exciting where you don't have to think so much to write a simple function. At 3-rd word getto code sort of fell together in few seconds and I tried it and it even worked. From then on things just got nicer and nicer (see the source file below).

: cutto ( sub str1 -- str2 ) dup >r dup length >r start r> r> subseq ;
: cutoff ( sub str1 -- str2 ) dupd cutto dup >r length swap length swap r> subseq ;
: getto ( sub str1 -- str2 ) tuck start 0 swap rot subseq ;
: cut-to swap cutto ;
: cut-off swap cutoff ;
: get-to swap getto ;
: snatch-to dupd get-to swap ;

What I want to do here? I want to prepare few words that will help me extract stuff out of a string in a reasonably elegant way.

( scratchpad ) "<A c=123&..><B c=234&..><C c=345&..><D c=456&..><E c=567&..>"
 			"<B" cut-to "c=" cut-off "&" snatch-to
 			"<D" cut-to "c=" cut-off "&" get-to .s
"234"
"456"

I don't know, but this seems very elegant to me.

click to see the full progress, comments and usage examples of these words

After I posted it on IRC channel #concatenative elasticdog quickly posted a lot more elegant variations of my tree base words:

: cutto tuck start tail ;
: cutoff swap split1 nip ;
: getto swap split1 drop ;

Beauty!!!

Read and let read :)
  • del.icio.us
  • Reddit
  • Digg
  • DZone
  • email
  • Facebook
  • HackerNews
  • Twitter
  • StumbleUpon

Leave a Reply