This exercise ask for implement cons
, car
and cdr
functions using only lambda functions.
The function cons(a,b)
create a list of a
followed by b
, car(l)
returns the first element of list l
, and cdr(l)
returns the rest of the list.
I got it working with lists of only two elements, but when you try to cons more elements it fails. Any Ideas?
#include <iostream>
#include <functional>
template<typename A>
A car( std::function< A(std::function<A(A,A)>) > m ){
return m( [](A a, A){ return a; } );
}
template<typename A>
A cdr( std::function< A(std::function<A(A,A)>) > m ){
return m( [](A, A b){ return b; } );
}
template<typename A>
std::function< A(std::function<A(A,A)>) >
cons( const A a, const A b){
return [=](std::function<A(A,A)> l){ return l(a,b); };
}
int main(){
//auto l = cons( cons( 1, 2 ), 3 ); // no matching function
auto l = cons( 1, 2 );
std::cout << car( l ) << ", " << cdr( l ) << std::endl;
return 0;
}
UPDATE
I notice that the real signature of cons should be:
template<typename A,typename B, typename C>
std::function< C(std::function<C(A,B)>) >
cons( const A a, const B b){
return [=](std::function<C(A,B)> l){ return l(a,b); };
}
Because this version also didn't work.
UPDATE 2 It can be simplified (more readable) with:
template<typename A, typename B, typename C>
using Cell<A,B,C> = std::function<C(A,B)>