Skip to content

Instantly share code, notes, and snippets.

@noskill
Created August 7, 2015 14:58
Show Gist options
  • Select an option

  • Save noskill/b24722c1bb0fbd11c02c to your computer and use it in GitHub Desktop.

Select an option

Save noskill/b24722c1bb0fbd11c02c to your computer and use it in GitHub Desktop.
Functional list
#include <iostream>
#include <memory>
template<class T>
struct Node
{
Node(T v, std::shared_ptr<const Node> tail): value(v), next(tail) {
// std::cout << "Node " << value << tail << std::endl;
};
const T value;
std::shared_ptr<const Node> next;
};
template<class T>
class List{
public:
List(): head(nullptr), size(0) {};
List(T val, List tail): head( std::make_shared<Node<T>>(val, tail.head) ), size(tail.size + 1) {
std::cout << "Size " << size << std::endl;
};
private:
size_t size;
std::shared_ptr<Node<T>> head;
explicit List (std::shared_ptr<Node<T>> item) : head(item), size(1) {};
public:
T front() const
{
assert(!isEmpty());
return head->value;
}
bool isEmpty(){
return head == nullptr;
}
List append(T value){
return List(value, *this);
}
size_t getSize() {
return size;
}
private:
List pop_front() const
{
assert(!isEmpty());
return List(head->next);
}
};
template<typename T>
void printList(List<T> * list){
return;
}
int main(int argc, char** argv){
std::cout << "Start" << std::endl;
List<int> list;
list = list.append(5);
list = list.append(3);
std::cout << list.getSize() << std::endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment