Question

I wish something like:

>> op : infix-func [self x] [ 2 * x + self ]
>> 3 op 2
== 7

It is possible?

Was it helpful?

Solution

Not currently possible, no. You can assign an existing operator to a new word in Rebol 3, and that new word will be an infix operator, but you can't make new operators from Rebol code.

If it did work it would probably currently look like make op! [[self x] [2 * x + self]]

Partially I think it's really just a matter of no one having gotten around to it. But it's open source now so maybe a concrete implementation proposal could be taken seriously.

The one caveat would be that the core Rebol evaluator gets a lot of benefit out of avoiding infix. Those few native infix operators were added as an appeasement to help the really basic things you might do like compare for equality look "normal". It's a balance to strike, and to ask whether if you are looking for new infix operators if what you really want is a dialect, lest a "sentence" of Rebol become harder to grok...

OTHER TIPS

You cannot define new infix operators but you do have 2 options:

  1. Redefine an existing infix operator like '+ or '= (strongly inadvisable)

  2. create a dialect of some sorts and wrap the code that you want in it As an example...

syntax: func [ block [ block! ] options [ block!] ] [

foreach op select options to-word "operators" [

  if find block op [

      segment1: copy/part back find block op 2

      segment2: reverse copy segment1

      replace/all block segment1 segment2

  ] 

]

do block

]

plus: func [ a b ] [

return: a + b

]

minus: func [ a b ] [

return: a - b

]

|: func [ a b ] [ print b ]

syntax [

print 1 plus 2

print 5 minus 7

1 | "done"

] [

operators [ plus minus | ]

]

will execute and will print out the following to the console.

3

-2

done

It will be easy to define even new tertiary operators or even new flow control structures using something like this. In this sample, I simply navigate along the series that has my code and swap the order (i.e. making "1 plus 2" effectively "plus 1 2"). A proper dialect (DSL) would likely use parse to provide something closer to a grammar

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top