DEV Community

Discussion on: Java Daily Coding Problem #005

Collapse
 
jckuhl profile image
Jonathan Kuhl • Edited

I'm not sure I fully understood what the question was asking, but I ended up with this:

// main.java:

package com.company;

public class Main {

    public static void main(String[] args) {
        Pair<Integer> p = Pair.cons(3,4);
        System.out.println("The pair is: " + p);
        Integer a = Pair.car(p);
        System.out.println("Output of Pair.car(): " + a);
        Integer b = Pair.cdr(p);
        System.out.println("Output of Pair.cdr(): " + b);
    }
}

// Pair.java

package com.company;

public class Pair<T> {

    private T a;
    private T b;

    public Pair(T a, T b) {
        this.a = a;
        this.b = b;
    }

    public static <T> Pair<T> cons(T a, T b) {
        return new Pair<T>(a, b);
    }

    public static <T> T car(Pair p) {
        return (T)p.a;
    }

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

    @Override
    public String toString() {
        return "(" + a + "," + b + ")";
    }
}

The cons function seemed redundant with the constructor but I implemented it anyways. Had to do some research in implementing generic static methods.

Collapse
 
awwsmm profile image
Andrew (he/him) • 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!