Home

Daily Coding Problem #5 - Higher Order Function

February 22, 2019

Problem

This problem was asked by Jane Street.

cons(a, b) constructs a pair, and car(pair) and cdr(pair) returns the first and last element of that pair. For example, car(cons(3, 4)) returns 3, and cdr(cons(3, 4)) returns 4.

Given this implementation of cons:

def cons(a, b):
    def pair(f):
        return f(a, b)
    return pair

Implement car and cdr.

Solution

If you’re familiar with the concept of higher-order function, this one should be relatively easy.

5_higher_order_function.go

package daily_coding_problem_in_go

type Pair struct {
	First int
	Second int
}

func Cons(a, b int) func() Pair {
	return func() Pair {
		return Pair{a,b}
	}
}

func Car(f func() Pair) int {
	return f().First
}

func Cdr(f func() Pair) int {
	return f().Second
}

Test case

5_higher_order_function_test.go

package daily_coding_problem_in_go

import "testing"

func TestCar(t *testing.T) {
	if actual := Car(Cons(3,4)); actual != 3 {
		t.Errorf("Expected 3 - got %v", actual)
	}
}

func TestCdr(t *testing.T) {
	if actual := Cdr(Cons(3,4)); actual != 4 {
		t.Errorf("Expected 4 - got %v", actual)
	}
}