• python
  • javascript
  • reactjs
  • sql
  • c#
  • java
Facebook Twitter Instagram
Devs Fixed
  • python
  • javascript
  • reactjs
  • sql
  • c#
  • java
Devs Fixed
Home » Resolved: In Raku, how does one create a Code object dynamically from a string?

Resolved: In Raku, how does one create a Code object dynamically from a string?

0
By Isaac Tonny on 17/06/2022 Issue
Share
Facebook Twitter LinkedIn

Question:

In Raku version v2022.06, I am trying to dynamically create grammar G having two productions …
  1. S → λ
  2. S → aSb

My draft program is …
Program output is …
The draft program shown above has $myTopCode and $mySCode hardcoded.
However, how does one dynamically (programmatically) create the Code objects $myTopCode and $mySCode from the pairs of strings in the @variableRightHandSidesMap ?

Update …


The answers below led me to the following draft, which produces the hoped‑for output (as shown above) …

use MONKEY-SEE-NO-EVAL ;

sub MAIN ( )
{
my @variableRightHandSidesMap is Array[Pair] ;
@variableRightHandSidesMap.push: Pair.new(“S”, “”) ;
@variableRightHandSidesMap.push: Pair.new(“S”, “‘a’ ‘b'”) ;

constant Parser := Metamodel::GrammarHOW.new_type( name => ‘Parser’ ) ;

my $startVariable = @variableRightHandSidesMap[0].key ; # ‘S’
my $myTopCode = EVAL ( ‘my token TOP { <' ~ $startVariable ~ '> }’ ) ;
Parser.^add_method( ‘TOP’, $myTopCode ) ;

my Str $sCumulativeRightHandSide = ” ;
loop ( my $i = 0 ; $i < @variableRightHandSidesMap.elems ; $i++ ) { if ( $i > 0 )
{
$sCumulativeRightHandSide ~= ( ‘ | ‘ ) ;
}
if ( @variableRightHandSidesMap[$i].value.chars <= 0 ) { $sCumulativeRightHandSide ~= ( '\'\'' ) ; } else { $sCumulativeRightHandSide ~= ( @variableRightHandSidesMap[$i].value ) ; } # end else } # end loop my $mySCode = EVAL ( 'my token ' ~ 'S' ~ ' { ' ~ $sCumulativeRightHandSide ~ ' }' ) ; Parser.^add_method( 'S', $mySCode ) ; Parser.^compose ; say Parser.HOW.^name ; say Parser.^methods( :local ) ; say ?(Parser.parse: 'aabb') ; say ?(Parser.parse: 'aaaaabbbbb') ; say ?(Parser.parse: 'aabbb') ; say ?(Parser.parse: 'abab') ; } # end sub MAIN [/code]

Any suggestions (such as those making the above draft more concise) would be appreciated.

Answer:

The EVAL function can be used to parse, compile, and evaluate Raku source. If you want to produce some kind of code object, then make sure the evaluated expression is a code object, e.g. EVAL 'anon regex { x }'.

If you have better answer, please add a comment about this, thank you!

raku regex
Share. Facebook Twitter LinkedIn

Related Posts

Resolved: std::regex_replace to replace multiple combinations

26/03/2023

Resolved: How can I copy files using the ansible.builtin.copy module and avoid conflicting file names?

26/03/2023

Resolved: Reshape tensors of unknown shape with tf.function

26/03/2023

Leave A Reply

© 2023 DEVSFIX.COM

Type above and press Enter to search. Press Esc to cancel.