Skip to content

Commit be4b707

Browse files
authored
Final Racket parser
1 parent 096da60 commit be4b707

File tree

1 file changed

+31
-3
lines changed

1 file changed

+31
-3
lines changed

_posts/2023-04-20-Lexer.md

Lines changed: 31 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -92,17 +92,19 @@ The result is this. The error condition is not tested.
9292
Tokens: [Literal '1',Plus,InvalidChar 'x',Literal '2']
9393
{% endhighlight %}
9494

95-
# Racket code
95+
# Typed Racket code
96+
97+
I read that Racket has many levels and types of languages and here I am using Typed Racket.
9698

9799
I have to note that this is my first ever Racket code and the intention is to port my haskell to Typed Racket.
98-
So I have explained what I learn using pieces of code. Neither the Racket code or Haskell code implementes
100+
So I have explained what I learnt using pieces of code. Neither the Racket code or Haskell code implementes
99101
the entire interpreter or even the lexer. The git repo. will have the entire code if I manage to learn
100102
Racket sufficiently to code the whole interpreter in the book.
101103

102104
## Step 1
103105

104106
This compiles without errors. But the code is not tested. I will add more test code while I refactor.
105-
In this case I have a feeling the the code is more verbose than the equivalent Haskell code.
107+
In this case I have a feeling that the code is more verbose than the equivalent Haskell code.
106108

107109
{% highlight racket %}
108110
#lang typed/racket
@@ -183,3 +185,29 @@ But this prints {% highlight racket %}#<Literal>{% endhighlight %} without the v
183185
This is the Racket way of printing the _struct_ with the value.
184186

185187
{% highlight racket %}(Literal 2){% endhighlight %}
188+
189+
## Step 2
190+
191+
This took longer than I expected as Racket seems to be very different than even Haskell. Many iterations later with help
192+
from Racket experts I was able to understand how to code the function.
193+
194+
{% highlight racket %}
195+
(: parse-exp (-> (U (Listof Char) )
196+
(Listof(U (ErrorType Integer Char) (Operator Char) ))))
197+
(define (parse-exp lst )
198+
(match lst
199+
['() (list(EndOfInput))]
200+
[(list x xs ...)
201+
(match x
202+
[(? char-numeric?) (cons (Literal x) (parse-exp xs))]
203+
[#\+ (cons (Plus) (parse-exp xs)) ]
204+
[_ (list (Unexpected 0)) ])]))
205+
206+
207+
{% endhighlight %}
208+
209+
The type of this function is only slightly different than the Haskell code and the error conditions
210+
are not tested fully. The _Offset_ of each charater is not tracked but that should not be difficult.
211+
212+
The output is {% highlight racket %}(list (Literal #\1) #<Plus> (Literal #\2) #<EndOfInput>){% endhighlight %}
213+

0 commit comments

Comments
 (0)