Seunghyun Yoo

Posts | Development | About

[EN] Print nested vectors (C++/OCaml)

C++ Version (Template):

template<typename T>
ostream& operator << (ostream& out, const vector<T>& v){
    out << "[";
    if (!v.empty()){
        for (auto itr = v.cbegin(); itr != --v.cend(); itr++){
            out << *itr << ",";
        }
        out << *--v.cend();
    }
    out << "]";
    return out;
}


int main()
{
    vector<int> m = {1,2,3,4};
    vector<vector<int>> n = { { 1, 2, 3, 4 }, { 5, 6 } };
    cout << m << endl; // [1,2,3,4]
    cout << n << endl; // [[1,2,3,4],[5,6]]
    return 0;
}

OCaml Version (Higher-Order Function):

let print_list print_function lst =
	print_string "[";
	let rec print_list_helper print_function lst =
		match lst with
		| [] -> ()
		| h::[] -> print_function h (* not to print out the unnecessary semicolon *)
		| h::t -> print_function h; print_string ";"; print_list_helper print_function t 
	in print_list_helper print_function lst;
	print_string "]";;

print_list (print_list print_int) [[1;2;3];[4;5;6]];;