Files
wren/example/set.wren
T
Kyle Marek-Spartz b949886707 feat: add contains method to List and update Set example to new operator syntax
Add a `contains(element)` method to the `List` class in the core library,
enabling linear search for an element across all list items. Update the
`example/set.wren` file to use the new Wren operator syntax for `|`, `+`,
`&`, and `-` methods, replacing old function-style parameter definitions
with block-style closures. Also fix trailing whitespace throughout the
Set example and embed the new `contains` method into the C source string
in `src/wren_core.c` for the built-in List class.
2015-01-09 22:02:40 +00:00

111 lines
1.7 KiB
Plaintext

class Set {
new {
_list = []
_clean = true
}
new (list) {
if (list is List) {
_list = list
_clean = false
cleanup
} // raise error?
}
cleanup {
// Removes duplicates in the underlying list.
if (!_clean) {
var newList = []
for (element in _list) {
if (!newList.contains(element)) newList.add(element)
}
_list = newList
_clean = true
}
}
add(element) {
_clean = false
_list.add(element)
}
remove(element) {
cleanup // Remove duplicates, so we can return early upon deletion.
for (i in 0.._list.count) {
if (_list[i] == element) {
_list.removeAt(i)
return
}
}
}
contains(element) {
return _list.contains(element)
}
count {
cleanup
return _list.count
}
iterate(i) {
cleanup
if (i == null) {
if (count > 0) return 0
return null
}
if (i < count || i >= count) return false
return i + 1
}
iteratorValue(i) {
cleanup
return _list[i]
}
map(f) {
return new Set(_list.map(f))
}
where(f) {
return new Set(_list.where(f))
}
|(that) {
// Union
return new Set(_list + that)
}
+(that) {
// A synonym for |
return this | that
}
&(that) {
// Intersection
return new Set(
_list.where { |element|
return that.contains(element)
} + that.where { |element|
return _list.contains(element)
})
}
-(that) {
// Set minus
return new Set(
_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))