Posts in this category

Mon, 31 May 2010

This Week's Contribution to Perl 6 Week 5: Implement Str.trans

Permanent link

For this week's contribution to Perl 6 we ask you to write some Perl 6 code that implements the trans method for Rakudo Perl. This is the backend for the tr/// operator.

(Introduction to this series of challenges)


The Perl 6 transliteration operator is also available as a method. It replaces all occurrences of some characters (or regexes) with a substitution string. The easiest case is:

say 'Hello World'.trans('a' => 'A', 'e' => 'E', 'O' => 'O');
# output: HEllO WOrld

say 'Hello World'.trans('aeo' => 'AEO');
# same thing

The previous iteration of Rakudo had a PIR-based (and complicated) implementation for trans. There are tests in the official test suite for .trans.

What you can do

Please write a method trans that implements part of the specification. Since it's quite a lot to do, it's OK to only do parts. For example I recommend to omit regexes altogether for now, and only implement literal string patterns. The easiest approach is probably to create a hash that maps each input pattern character to the transliteration, and walk the string character by character by iterating over self.comb.

To test it without actually having to recompile Rakudo after each change, I recommend to copy the test that Rakudo can parse (ie the method tests, not the tests for tr///), and start it with

use v6;

use Test;

augment class Str {
    method trans(*@patterns)  {
        # do your hacking here
        'wrong return value';

plan *;

is("ABC".trans( ('A'=>'a'), ('B'=>'b'), ('C'=>'c') ),
    "Each side can be individual characters");

is("XYZ".trans( ('XYZ' => 'xyz') ),
    "The two sides of the any pair can be strings interpreted as tr/// would multichar");




Please send your submission to the mailing list, and set me ( as CC, because the mailing list sometimes has a large delay.

If you have any questions, please ask the mailing list, me or (preferred) on our IRC channel, #perl6.

The best/most extensible/most complete/prettiest/whatever submission will make it into the next release of Rakudo.

Update: There have been two submissions discussed on perl6-compiler, and another one submitted as gist. If you want to work on this challenge, please improve one of the existing submissions, not write a new one from scratch.

[/perl-6] Permanent link

Comments / Trackbacks:

Trackback URL: /blog-en.trackback

Write a comment

URL: [] (optional)
Title: (optional)
Save my Name and URL/Email for next time