Skip to content

Commit

Permalink
Rewrote squeeze in rascal
Browse files Browse the repository at this point in the history
  • Loading branch information
DavyLandman committed Jul 2, 2024
1 parent 2dc75e6 commit 90d5afe
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 34 deletions.
25 changes: 0 additions & 25 deletions src/org/rascalmpl/library/Prelude.java
Original file line number Diff line number Diff line change
Expand Up @@ -3040,31 +3040,6 @@ public IString trim(IString s) {
return values.string(s.getValue().trim());
}

public IString squeeze(IString src, IString charSet) {
final Pattern isCharset = Pattern.compile("[" + charSet.getValue() + "]", Pattern.UNICODE_CHARACTER_CLASS);
StringBuilder result = new StringBuilder(src.length());
var chars = src.iterator();
int previousMatch = -1;
while (chars.hasNext()) {
int cp = chars.nextInt();
if (cp == previousMatch) {
// swallow
continue;
}

String c = Character.toString(cp);
if (isCharset.matcher(c).matches()) {
previousMatch = cp;
// swallow the next
}
else {
previousMatch = -1;
}
result.append(c);
}
return values.string(result.toString());
}

public IString capitalize(IString src) {
StringBuilder result = new StringBuilder(src.length());
boolean lastWhitespace= true;
Expand Down
11 changes: 9 additions & 2 deletions src/org/rascalmpl/library/String.rsc
Original file line number Diff line number Diff line change
Expand Up @@ -519,8 +519,15 @@ import String;
squeeze("hello", "el");
```
}
@javaClass{org.rascalmpl.library.Prelude}
public java str squeeze(str src, str charSet);
public str squeeze(str src, str charSet) {
if (charSet == "") {
return src;
}
return visit(src) {
case /<c:.><c>+/ => c
when /[<charSet>]/ := c
}
}
Expand Down
14 changes: 7 additions & 7 deletions src/org/rascalmpl/library/lang/rascal/tests/basic/Strings1.rsc
Original file line number Diff line number Diff line change
Expand Up @@ -249,15 +249,15 @@ test bool tstSplit(str S1, str S2) = areOverlapping(S1,S2) || isEmpty(S1) || isE

// squeeze

private str rascalSqueeze(str s, str charSet) {
return visit (s) {
case /<c:.>(<c>)+/ => "<c>"
when /[<charSet>]/ := c
};
test bool tstSqueeze1(str S) = /<c:[a-zA-Z]><c>/ !:= squeeze(S, "a-zA-Z");
test bool tstSqueeze2(str S) = squeeze(S, "") == S;
test bool tstSqueeze3(str S) {
if (/<c:[a-z]><c>/ := S) {
return /<c><c>/ := squeeze(S, "0-9");
}
return true;
}

test bool tstSqueeze1(str S) = rascalSqueeze(S, "a-zA-Z") == squeeze(S, "a-zA-Z");


test bool tstStartsWith(str S1, str S2) = startsWith(S1+S2, S1);

Expand Down

0 comments on commit 90d5afe

Please sign in to comment.