4 ms·
I don't really write Java, but I fail to see any easy and robust way to assign a type to the flatten function in Java. Is this the signature you would expect i
by wz1000 10y ago
I don't really write Java, but I fail to see any easy and robust way to assign a type to the flatten function in Java.
Is this the signature you would expect in a solution to this?
List<Integer> flatten(List<Object>)
Or something like
List<Integer> flatten(NestedList<Integer>)
with a definition for NestedList?
Is there even a way to define something like NestedList without coercing back and forth from Object? Is there a way you can do this so that you don't have to basically reimplement List?
- ng12 10y agoI would either use Object to be quick, or implement a NestedListItem with isNumber(), getNumber(), getList(). The one thing I do like about this problem is it shows when TDD is useful. If you try to write a test case first the representation problem will be the very first thing you run into, and the code will mostly follow from there.
- wz1000 10y agoPersonally, I think this problem shows why sane type systems are useful. In Haskell data NestedList a = Single a | Nested [NestedList a] -- Or equivalently, type NestedList = Free [] flatten :: NestedList a -> [a] -- This is pretty much the only reasonable definition of flatten the compiler will accept given this type flatten (Single a) = [a] flatten (Nested xs) = concatMap flatten xs -- or given the Free variation of NestedList -- flatten = retract
- dllthomas 10y agoNot necessarily. See my bash solution in another comment :-D
- dllthomas 10y agoAlso not a Java programmer, but my approach would probably involve two classes implementing the nested list interface. One would hold a list, the other an integer (or maybe parameterize over that, depending on the context). Drawing analogy to lisp, we need to be able to answer "is this a list or an atom?" Note that the actual structure involved is "really" a rose tree.