4 ms·
Yes, through duck typing. At some parts of my code near the entry point I might not care about what the input "file" is, but later (or the underlying library) f
by franciscop 8y ago
Yes, through duck typing. At some parts of my code near the entry point I might not care about what the input "file" is, but later (or the underlying library) for instance might accept both a path or an object for instance.
This is specially useful for options that are not used near the entry point, but instead are passed down. If the later implementation changes, you'd have to change the middle implementation as well to accept the new/different types.
- int_19h 8y agoDuck typing is completely orthogonal to dynamic typing - you can have static duck typing. C++ templates are one well-known example, but OCaml's intersection of its OO system with type inference also makes it kinda duck typed - e.g. if you define a function that calls a method on an argument, the type of argument is inferred as "some object that has a method with such-and-such name and types". If you call another method, that also gets added etc. But it's still statically typed - at call site, the actual type of the argument must have those methods, or it won't compile. Or, getting back to C++, we have polymorphic lambdas there now (which are implemented in terms of templates, but with syntactic sugar that makes it all much cleaner): auto f = [&](auto x, auto y) { return x + y; }; cout << f(1, 2); // 3 cout << f("a"s, "b"s); // "ab" cout << f("abcd", 2); // "cd" cout << f(main, true); // compile-time error Again, all statically typed, although the type checking basically consists of substituting the types in the body and checking if the result makes sense. Which is to say, the error messages from such code are very similar to the ones you get in e.g. Python if you have the types wrong, except here the errors are compile-time, not runtime.
- jimbo1qaz 8y agoThe Agg C++ library defines every class as a template, taking duck-typed parameters: - type of Agg object passed into object - type of "algorithm" used (or similar) I read matplotlib's Agg C++ backend. Guessing which Class A could be passed into various template parameters in Class B was miserable because of duck typing. And it also broke "jump to definition". ``` Class B<A> { A a; } this->a.foo(), but you don't know what type a is. ```
- machiaweliczny 8y agoAll languages with structural typing support duck typing out of the box.