Skip to content

Instantly share code, notes, and snippets.

@nd3i
Last active July 13, 2024 16:28
Show Gist options
  • Save nd3i/86b89bc396515ce6484afc92803e2248 to your computer and use it in GitHub Desktop.
Save nd3i/86b89bc396515ce6484afc92803e2248 to your computer and use it in GitHub Desktop.
## Returns a hash of character positions for the given string
## cp('aabb') --> {a => [0,1], b => [2,3]}
##
sub cp(Str $s --> Hash) {
(^($s.chars)).classify({ substr($s, $_, 1) })
}
## Inverse of cp (apply join() to get the string)
##
sub pc(#`(Hash) %cp --> Array) {
my @s;
@s[.value.List] = (.key xx .value.elems) for %cp;
@s
}
my $s = 'alpha';
say "'$s' --> ", $s.&cp;
say '{...} --> ', $s.&cp.&pc;
$ raku cppc.raku
'alpha' --> {a => [0 4], h => [3], l => [1], p => [2]}
{...} --> [a l p h a]
## ... uncomment 'Hash' on line 10 ...
$ raku cppc.raku
'alpha' --> {a => [0 4], h => [3], l => [1], p => [2]}
Type check failed in binding to parameter '%cp'; expected Associative[Hash] but got Hash[Any,Mu] ((my Any %{Mu} =
:a($...)
in sub pc at cppc.raku line 10
in block <unit> at cppc.raku line 20
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment