1
0
forked from Mirror/wren

Update set example to new Syntax. Replaces #30

This commit is contained in:
Kyle Marek-Spartz
2015-01-09 16:02:40 -06:00
parent fa85bb1eef
commit c0b0920d67
3 changed files with 49 additions and 24 deletions

View File

@ -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 {}

View File

@ -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))

View File

@ -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";