Skip to content

Commit

Permalink
Add contains to Listing
Browse files Browse the repository at this point in the history
  • Loading branch information
holzensp committed Oct 14, 2024
1 parent bd7c4c8 commit e55463f
Show file tree
Hide file tree
Showing 4 changed files with 47 additions and 0 deletions.
17 changes: 17 additions & 0 deletions pkl-core/src/main/java/org/pkl/core/stdlib/base/ListingNodes.java
Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,23 @@ protected VmListing eval(VmListing self, VmFunction selector) {
}
}

public abstract static class contains extends ExternalMethod1Node {
@Specialization
protected boolean eval(VmListing self, Object element) {
var result = new MutableBoolean(false);
self.forceAndIterateMemberValues(
(key, member, value) -> {
if (element.equals(value)) {
result.set(true);
return false;
}
return true;
});
LoopNode.reportLoopCount(this, self.getLength());
return result.get();
}
}

public abstract static class fold extends ExternalMethod2Node {
@Child private ApplyVmFunction2Node applyLambdaNode = ApplyVmFunction2NodeGen.create();

Expand Down
12 changes: 12 additions & 0 deletions pkl-core/src/test/files/LanguageSnippetTests/input/api/listing.pkl
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,10 @@ local duplicate: Listing<Person> = (base) {
new { name = "Elf Owl" }
}

local altered: Listing<Person> = (base) {
[0] { name = "Wood Pigeon" }
}

facts {
["isEmpty"] {
empty.isEmpty
Expand Down Expand Up @@ -112,6 +116,14 @@ facts {
base.singleOrNull == null
new Listing { 42 }.singleOrNull == 42
}

["contains"] {
!empty.contains(0)
base.contains(base[1])
derived.contains(base[1])
derived.contains(derived[3])
!altered.contains(base[0])
}
}

examples {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,13 @@ facts {
true
true
}
["contains"] {
true
true
true
true
true
}
}
examples {
["length"] {
Expand Down
11 changes: 11 additions & 0 deletions stdlib/base.pkl
Original file line number Diff line number Diff line change
Expand Up @@ -1916,6 +1916,17 @@ class Listing<out Element> extends Object {
@AlsoKnownAs { names { "uniqueBy" } }
external function distinctBy(selector: (Element) -> Any): Listing<Element>

/// Tests if [element] is contained in this listing.
///
/// Facts:
/// ```
/// new Listing { 1 ; 2 ; 3 }.contains(1)
/// new Listing { 1 ; 2 ; 3 }.contains(2)
/// new Listing { 1 ; 2 ; 3 }.contains(3)
/// !new Listing { 1 ; 2 ; 3 }.contains(4)
/// ```
external function contains(element: Element): Boolean

/// Folds this listing in iteration order using [operator], starting with [initial].
external function fold<Result>(initial: Result, operator: (Result, Element) -> Result): Result

Expand Down

0 comments on commit e55463f

Please sign in to comment.