|
140 | 140 | (NONE)
|
141 | 141 | ) (ID)
|
142 | 142 |
|
| 143 | +SEARCH_AND_REPLACE_VARIABLE_IN_TERM = Y ( |
| 144 | + lambda f: |
| 145 | + lambda i: |
| 146 | + lambda argument: |
| 147 | + lambda term: term (TRUE) |
| 148 | + (lambda _: EQ (i) (term (FALSE)) (argument) (term)) |
| 149 | + (lambda _: BUILD_ABSTRACTION (f (INCR (i)) (argument) (term (FALSE)))) |
| 150 | + (lambda _: BUILD_APPLICATION |
| 151 | + (f (i) (argument) (term (FALSE) (TRUE))) |
| 152 | + (f (i) (argument) (term (FALSE) (FALSE)))) |
| 153 | + (NONE) |
| 154 | +) (ZERO) |
| 155 | + |
143 | 156 | # It effectively runs a parsed BLC expression. Starting from the outermost
|
144 | 157 | # application, variables are matched with the bound variable and replaced
|
145 | 158 | # accordingly. This reduction strategy is known as 'call by name'.
|
146 | 159 | #
|
147 |
| -# - If it's a variable, then leave it as it is. |
148 |
| -# - If it's an abstraction, then replace the bound term inside the body. At the |
149 |
| -# first call this doesn't happen! |
150 |
| -# - If it's an application, then the bound term becomes the argument. |
151 |
| -# |
152 | 160 | # Readings on lambda reduction:
|
153 | 161 | # - 'Types and Programming Languages', by Thomas Pierce
|
154 | 162 | # - http://www.cs.yale.edu/homes/hudak/CS201S08/lambda.pdf
|
155 | 163 | # - https://en.wikipedia.org/wiki/Reduction_strategy_(lambda_calculus)
|
156 |
| -TERM_TO_NORMAL_FORM = ID #Y ( |
157 |
| -# lambda f: |
158 |
| -# lambda current_index: |
159 |
| -# lambda term: |
160 |
| -# lambda expression: |
161 |
| -# expression (TRUE) |
162 |
| -# (ID) |
163 |
| -# (lambda abstraction: BUILD_ABSTRACTION |
164 |
| -# # We increment the counter 'n' and keep searching for terms bound to 'x'. |
165 |
| -# (f (expression (FALSE)) (INCR (current_index)) (term))) |
166 |
| -# (lambda application: f (INCR (current_index)) (application (FALSE) (FALSE)) (application (FALSE) (TRUE))) |
167 |
| -#) (ZERO) (NONE) |
| 164 | +TERM_TO_NORMAL_FORM = Y ( |
| 165 | + lambda f: |
| 166 | + lambda term: term (TRUE) |
| 167 | + (ID) |
| 168 | + (ID) |
| 169 | + (lambda _: term (FALSE) (TRUE) (TRUE) |
| 170 | + (ID) |
| 171 | + (lambda _: f (SEARCH_AND_REPLACE_VARIABLE_IN_TERM |
| 172 | + (term (FALSE) (FALSE)) |
| 173 | + (term (FALSE) (TRUE) (FALSE)))) |
| 174 | + (lambda _: f (BUILD_APPLICATION (f (term (FALSE) (TRUE))) (term (FALSE) (FALSE)))) |
| 175 | + (term)) |
| 176 | + (term) |
| 177 | +) |
168 | 178 |
|
169 | 179 | VARIABLE_TO_STRING = Y (
|
170 | 180 | lambda f:
|
|
198 | 208 | lambda char:
|
199 | 209 | CHAR_IS_EOF (char)
|
200 | 210 | (lambda _: check_syntax (char)
|
201 |
| - # TODO: reduce to normal form. |
202 | 211 | (lambda _: TERM_TO_STRING (TERM_TO_NORMAL_FORM (parser)))
|
203 | 212 | (lambda _: '<invalid program>')
|
204 | 213 | (NONE))
|
|
0 commit comments