DEV Community

loading...

Discussion on: Java Daily Coding Problem #005

Collapse
awwsmm profile image
Andrew (he/him) Author • Edited

Yeah, see this is what I think the question implies, but it's not actually what the example Python code does. The Python code given, if followed, makes the problem needlessly complex. My first instinct was to do something like your solution, but I ended up trying to stick as closely to the prompt as possible, and that includes returning a partially-defined function from const.

Some notes on yours:

Defining Pair<T> with only one generic type means that a and b must be the same type. They can't be Integer and Double, for instance. Maybe try expanding it so a and b can have independent types?

Your return statements from cdr() and car() have explicit type-casting:

        return (T)p.b;

...if you instead declare the type of Pair in the argument, you can avoid this. Instead of:

    public static <T> T cdr(Pair p) {
        return (T)p.b;
    }

...write:

    public static <T> T cdr(Pair<T> p) {
        return p.b;
    }

Also, I think you can drop the <T> in the methods, since you already declare T in the class signature:

    public static T cdr(Pair<T> p) {
        return p.b;
    }

Other than that, that's basically what I would have written, if we needed to make a Pair class. Nice work!