-
-
Save noskill/b24722c1bb0fbd11c02c to your computer and use it in GitHub Desktop.
Functional list
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #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