2 ms·
C#: public static class EnumerableExtensions { public static IEnumerable<R> FilterMap<T, R>(this IEnumerable<T> list, Func<T, Option<R>> callba
by munificent 15y ago
C#:
public static class EnumerableExtensions
{
public static IEnumerable<R> FilterMap<T, R>(this IEnumerable<T> list, Func<T, Option<R>> callback)
{
...
}
}
There are some methods that need to be part of the class and carried around with the instance so that things like polymorphism work. But many operations work perfectly fine without. By making those lexically scoped, you avoid the problems of monkey-patching and method collisions. Extension methods are fantastic for this.
Also, for kicks, Magpie:
def (items) filterMap(callback)
var result = []
for item in items do
match callback(item)
case true, mapped then items add(mapped)
else nothing
end
end
result
end
var result = [1, 2, 3, 4, 5, 6] filterMap with
if it % 2 == 0 then (true, it * 2)
end
print(result) // 4, 8, 12
Magpie is dynamically-typed, but methods are lexically-scoped (and are multimethods).
- benmmurphy 15y agoyou have the same problem in C#. you can't take a Foo class and extend it from outside to have all the IEnumerable methods then let it have all the IEnumerable extension methods.