baum

view baum.c @ 1:3da0ff17c8e7

added features (print, sum, number); split in header file
author meillo@marmaro.de
date Thu, 07 Feb 2008 14:31:02 +0100
parents 2f71d692d4f9
children 557fa4df2bcd
line source
1 /*
2 * baum - an esoteric programming language
3 *
4 * (c) markus schnalke <meillo@marmaro.de>
5 * and julian forster
6 *
7 */
10 #include <stdio.h>
11 #include <stdlib.h>
12 #include <string.h>
14 #include "baum.h"
16 char action(struct Node* node);
18 struct Node* root;
21 void logit(char* text) {
22 fprintf(stderr, "[%s]\n", text);
23 }
26 /* new */
27 struct Node* newNode(char* name) {
28 struct Node* node;
29 node = (struct Node*) malloc(sizeof(struct Node));
30 node->name = name;
31 node->value = 0;
32 node->right = 0;
33 node->down = 0;
34 return node;
35 }
38 /* delete */
39 void delete(struct Node* node) {
40 if (node->down != NULL) {
41 delete(node->down);
42 }
43 if (node->right != NULL) {
44 delete(node->right);
45 }
46 free(node); node=0;
47 }
50 /* print */
51 void printNode(struct Node* node) {
52 printf("Node: %20s (%c)\n", node->name, node->value);
53 }
55 void printTree(struct Node* root) {
56 printNode(root);
57 printf(" down: ");
58 if (root->down != NULL) {
59 printTree(root->down);
60 } else {
61 printf("NULL\n");
62 }
63 printf(" right: ");
64 if (root->right != NULL) {
65 printTree(root->right);
66 } else {
67 printf("NULL\n");
68 }
69 }
72 char action_print(struct Node* node) {
73 printf("%c\n", action(node->down));
74 return 0;
75 }
77 char action_sum(struct Node* node) {
78 struct Node* tp;
79 tp = node->down;
80 while (tp != NULL) {
81 node->value += action(tp);
82 tp = tp->right;
83 }
84 return node->value;
85 }
87 char action_number(struct Node* node) {
88 return node->value;
89 }
91 char action(struct Node* node) {
92 if (strcmp(node->name, "print") == 0) {
93 logit("print-node");
94 return action_print(node);
95 } else if (strcmp(node->name, "sum") == 0) {
96 logit("sum-node");
97 return action_sum(node);
98 } else if (strcmp(node->name, "number") == 0) {
99 logit("number-node");
100 return action_number(node);
101 } else {
102 fprintf(stderr, "unknown kind of node");
103 exit(1);
104 }
105 }
109 /* traverse */
110 void traverse(struct Node* root) {
111 /* each node controlls the nodes below itself */
112 action(root);
113 }
115 /* init */
116 void init() {
117 root = newNode("print");
118 root->down = newNode("number");
119 root->down = newNode("sum");
120 root->down->down = newNode("number");
121 root->down->down->value = 70; /* 'F' */
122 root->down->down->right = newNode("number");
123 root->down->down->right->value = 50; /* '2' */
124 /* result should be 'x' */
125 }
128 /* main */
129 int main(int argc, char* argv[]) {
130 init();
131 printTree(root);
133 action(root);
135 delete(root);
137 return(0);
138 }