krfkeith / slate-language

Automatically exported from code.google.com/p/slate-language
MIT License
1 stars 0 forks source link

Allowing blocks with 0 or N slots as callbacks #26

Open GoogleCodeExporter opened 9 years ago

GoogleCodeExporter commented 9 years ago
Sometimes there is useful information to pass to a callback block, which
the programmer may or may not want to use. Currently, if you call a block
it *has* to have an arity of whatever the caller expects - which makes
sense, of course, but it blocks out the possibility of passing values that
the block may or may not use.

As a small example, say there's a method #times: on Number traits, used
like so:

    10 times: [inform: 'Hi!'].

This is the same as #timesRepeat. There *is* a value that could possibly be
useful to pass as an argument, but if you pass it the block must accept it,
even if the programmer doesn't want to use it.

An alternative calling method could determine the callback's arity and
decide based on that whether or not to call the block with the value,
allowing for both of these:

    10 times: [inform: 'Hi!'].
    10 times: [ | :n | inform: 'Counting down... ' ; n printString ].

Which is simple to implement:

    m@(Method traits) applySome: args
    [ m arity isZero ifTrue: [^ m do].
      m applyTo: args
    ].

    n@(Number traits) times: m@(Method traits)
    [ n isZero ifTrue: [^ Nil].
      m applySome: {n}.
      (n - 1) times: m
    ].

Original issue reported on code.google.com by suraci.a...@gmail.com on 7 Feb 2010 at 10:39

GoogleCodeExporter commented 9 years ago
Notably, one current work-around is to declare a block to have "[| *_ |" as an 
input 
header, which means it accepts any number of arguments and notionally discards 
them 
all.

However, passing arguments to such a block will currently allocate an array of 
the 
arguments on each invocation, which is costly. Also I am in agreement that this 
is an 
undesirable kind of effort to go through. So I will see about an efficient 
idiom for this 
kind of situation.

Original comment by BrianTRice on 14 Feb 2010 at 10:38