Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

About this user

crat

« Newer Snippets
Older Snippets »
Showing 1-2 of 2 total  RSS 

each with bind

using bind again ..

here's a version of a ruby/smalltalk-like each in rebol:

in smalltalk you can write:

collectionObject each: [:thing | thing printName ]
ruby used the same idea etc
- a  code block is passed to an object

here's a rebol version

collection: make object! [
 data: copy []

 each: func [blk [block!] 
             /local iterator statement ][
             iterator:  to word! first blk
             statement:  copy skip blk 1
             foreach item data [
                set iterator item
                do bind statement iterator
             ]
        ]
]

This works by taking an input block of the form :
  [ :x   print x ]
or
[ :num  add total num ] etc

iterator: to word! first blk
just sets up iterator to be a work like a or x ( not a get-word like :a or :x )

I use a get-word just as a smalltalkish reminder that this is a
dummy variable ( [ a print a] would work too)

statement: copy skip blk 1 
just makes a copy of the rest of input block
ie statement would be [print x] say , i suppose chopping off the first would work too..

within the loop we set the value of this word ( say x) to 
successive items  in the internal datablock, so the word we indirectly talking about has a different value each time round.

do bind statement iterator

interprets the statement using the current value of the word and do executes it.

people: make collection [
 data: ["fred" "george" "mary" "jane"]
]

people/each [:person print rejoin ["Hello " person]]
Hello fred
Hello george
Hello mary
Hello jane
>>

I guess there might be probs if the "dummy" variable was
also a word used internally by the object containing the each method .

script an object using bind

Suppose you have a robot object with methods like
move , attack etc. You can store a "script" in a block to automate the object

rebol []

robot: make object! [
move: func [amount] [...] ; whatever
turn: func [angle][..] 
fire: func [] [...]
run: func [code][
                   do bind code 'self
]
]

script: [
           move 100
           turn 45
           fire
           turn 23
           move 34
]
; etc

robbie: make robot []

robbie/run script

« Newer Snippets
Older Snippets »
Showing 1-2 of 2 total  RSS