3 ms·
This is heavy biased to C++, which is a language that already has too many features that people just want to use. This is a very specific case to be placed as a
by lucasoshiro 1y ago
This is heavy biased to C++, which is a language that already has too many features that people just want to use. This is a very specific case to be placed as a language feature, and could be just a lib.
If this becomes a C++ feature, imagine how many data structures we would need to support?
Many other languages, specially the FP languages, allow to do that as a library. Even the languages that are only inspired by FP. Example, Ruby:
class BinTree
include Enumerable
def initialize v, l, r
@v, @l, @r = v, l, r
end
def each &block
@l.each(&block) unless @l.nil?
yield @v
@r.each(&block) unless @r.nil?
end
end
Using the Enumerable mixin includes many FP-based methods, such as map, filter and reduce by only defining each, which in this case is DFS.
Then we can proceed to define a binary tree:
tree = BinTree.new(
1,
BinTree.new(
2,
BinTree.new(4, nil, nil),
BinTree.new(5, nil, nil)
),
BinTree.new(
3,
BinTree.new(6, nil, nil),
BinTree.new(7, nil, nil),
)
)
Iterate over all the elements:
tree.each{|v| puts v}
Iterate over the even elements:
tree.filter{|v| v.even?}.each{|v| puts v}
Stop iteration when finding a value:
tree.each do |v|
break if v == 1
puts v
end
And so on. The same can be done in Python, Kotlin and many others.
- monkeyelite 1y ago> If this becomes a C++ feature, imagine how many data structures we would need to support? C++ already solved that problem. Iterator are designed so that an algorithm can be written once and used with multiple data structures.
- lucasoshiro 1y agoSo we can go back to just use them and just write a new library
- monkeyelite 1y agoYou don’t need the standard library to make iterators.
- lucasoshiro 1y agoSo you can use it. I really don't see your point