diff --git a/builtin/core.wren b/builtin/core.wren index 91695011..da6e46a4 100644 --- a/builtin/core.wren +++ b/builtin/core.wren @@ -41,6 +41,15 @@ class List is Sequence { } return result } + + contains(element) { + for (item in this) { + if (element == item) { + return true + } + } + return false + } } class Range is Sequence {} diff --git a/example/set.wren b/example/set.wren index 3d0a0be3..b13f38de 100644 --- a/example/set.wren +++ b/example/set.wren @@ -3,7 +3,7 @@ class Set { _list = [] _clean = true } - + new (list) { if (list is List) { _list = list @@ -11,7 +11,7 @@ class Set { cleanup } // raise error? } - + cleanup { // Removes duplicates in the underlying list. if (!_clean) { @@ -28,7 +28,7 @@ class Set { _clean = false _list.add(element) } - + remove(element) { cleanup // Remove duplicates, so we can return early upon deletion. for (i in 0.._list.count) { @@ -38,7 +38,7 @@ class Set { } } } - + contains(element) { return _list.contains(element) } @@ -47,17 +47,17 @@ class Set { cleanup return _list.count } - + iterate(i) { cleanup if (i == null) { if (count > 0) return 0 return null } - if (i < count || i >= count) return false + if (i < count || i >= count) return false return i + 1 } - + iteratorValue(i) { cleanup return _list[i] @@ -66,38 +66,45 @@ class Set { map(f) { return new Set(_list.map(f)) } - + where(f) { return new Set(_list.where(f)) } - - | that { + + |(that) { // Union return new Set(_list + that) } - - + that { + + +(that) { // A synonym for | return this | that } - - & that { + + &(that) { // Intersection return new Set( - _list.where(fn (element) { + _list.where { |element| return that.contains(element) - }) + that.where(fn (element) { + } + that.where { |element| return _list.contains(element) - })) + }) } - - - that { + + -(that) { // Set minus return new Set( - _list.where( - fn (element) { - return ( - !that.contains(element)) - })) + _list.where { |element| + return !that.contains(element) + }) } } + +var a = "a" +var as = new Set([a, a, a]) + +var b = "b" +var bs = new Set([b, b, b]) + +IO.write((as | bs).contains(b)) +IO.write((as & bs).contains(a)) diff --git a/src/wren_core.c b/src/wren_core.c index 544f39f0..c4f4392c 100644 --- a/src/wren_core.c +++ b/src/wren_core.c @@ -84,6 +84,15 @@ static const char* libSource = " }\n" " return result\n" " }\n" +"\n" +" contains(element) {\n" +" for (item in this) {\n" +" if (element == item) {\n" +" return true\n" +" }\n" +" }\n" +" return false\n" +" }\n" "}\n" "\n" "class Range is Sequence {}\n";