How to parse string to list in typed racket

57 Views Asked by At

I am working on writing a simple parser in typed Racket, and as part of it, I want to parse string representations of s-expressions to lists as follows:

"(+ 1 (/ 2 (inc 0)))" => (list '+ 1 (list '/ 2 (list 'inc 0 ))). Is there an easy way to do this?

1

There are 1 best solutions below

0
Álvaro Radajczyk On

i'm not sure how you exactly expect the conversion result works, but i have to proposals for you.

Supposing this is the current behaviour of your list:

> (list-ref (list '+ 1 (list '/ 2 (list 'inc 0 ))) 0 )
+
> (list-ref (list '+ 1 (list '/ 2 (list 'inc 0 ))) 1 )
1
> (list-ref (list '+ 1 (list '/ 2 (list 'inc 0 ))) 2 )
(/ 2 (inc 0))

The first one

(read (open-input-string "(+ 1 (/ 2 (inc 0)))" ) )

This will work exactly as your current list (executing in console):

> (list-ref (read (open-input-string "(+ 1 (/ 2 (inc 0)))" ) ) 0)
+
> (list-ref (read (open-input-string "(+ 1 (/ 2 (inc 0)))" ) ) 1)
1
> (list-ref (read (open-input-string "(+ 1 (/ 2 (inc 0)))" ) ) 2)
(/ 2 (inc 0))

The second one

(read (open-input-string (string-replace "(+ 1 (/ 2 (inc 0)))" "(" "(list '") ) )

This will convert the input string exactly as your desired output, an then convert it into list (executing in console):

> (list-ref (read (open-input-string (string-replace "(+ 1 (/ 2 (inc 0)))" "(" "(list '") ) ) 0)
list
> (list-ref (read (open-input-string (string-replace "(+ 1 (/ 2 (inc 0)))" "(" "(list '") ) ) 1)
'+
> (list-ref (read (open-input-string (string-replace "(+ 1 (/ 2 (inc 0)))" "(" "(list '") ) ) 2)
1
> (list-ref (read (open-input-string (string-replace "(+ 1 (/ 2 (inc 0)))" "(" "(list '") ) ) 3)
(list '/ 2 (list 'inc 0))

I hope this was helpful for you! Let me know if something gone wrong!