Parsing a non-number in a string

I am parsing a string like “1 2 [Any]”. The 1 an 2 parse into Ints just fine, but how can I get [Any] to parse into an array? parse(Any,s[3]) returns an error, as does parse(,s[3]). Please advise.

use with caution

julia> s = "[Any]"
"[Any]"

julia> eval(Meta.parse(s))
1-element Vector{DataType}:
 Any

Before you do this - what do you want "[Any]" to mean? As it stands, from a julia point of view, this is a very unusual vector. If you have to resort to something like eval(Meta.parse(s)), you’re on the wrong road the vast majority of time.

2 Likes

{Any} could mean something like “1 2 [dup *]”.

In which case, what is dup? Do you mean you just want to parse anything between [ and ] as a vector…?

You’ll have to at least know what kind of data the vector should hold.

1 Like

Trying eval(Meta.parse(s)) gives this error – ERROR: Base.Meta.ParseError(“unexpected “]””)

I want the vector to hold any datatype.

can you show a MWE? (minimal working example) and what you’re trying to achieve?

It will help to get some background. Why are you parsing strings into Julia code?

2 Likes

duo is a function.

I’m implementing a concatinative language in julia. Similar to Forth.

I think you need to provide a copy-pastable example that reproduces the problem exactly, and show what output you want.

What is s?

1 Like

You probably want to write your own parser then. You can use Base for simple things like parsing numbers but more complicated objects you might be best of parsing yourself.

5 Likes

It won’t work to use the Julia parser because Julia has different syntax from Forth.

I do a readline to get user input. The string " 1 2 [dup *] should result in all three items being pushed onto a stack.

although there are a lot of DSL in Julia (in the form of macros), I think it is a pretty common opinion that languages that are good at being parser/compiler are different from other languages. The macros in Julia are essentially still combing back to Julia’s syntax in the end.

In this case I think Julia is not what you want to use to implement another language

1 Like

I think Julia could be good for implementing languages, but you will have to write your own function for converting strings into syntax trees, aka a parser. (That’s not specific to Julia however.)

1 Like

That’s too bad.I really wanted the new language to inherit all the features and functionality of Julia.

Many thanks for the replies!

Maybe what you want is an embedded DSL, e.g. in a nonstandard string literal, to take your Forth and turn it into Julia.

3 Likes