🎓 A1Learner
🔍
0 of 48 lessons completed

Julia Project: Mini Language

A mini language is a small set of text rules for writing arithmetic that a program can read and run. This lesson parses small arithmetic expressions and evaluates them.

Parse text, then evaluate it

Meta.parse turns the text into an expression value. Evaluating that value returns 5.

println(eval(Meta.parse("2 + 3")))
println(typeof(Meta.parse("2 + 3")))

Arithmetic order still applies

The first expression multiplies before it adds. The second expression adds first because of the brackets.

println(eval(Meta.parse("2 * 3 + 4")))
println(eval(Meta.parse("(2 + 3) * 4")))

A parsed expression can use a variable

The variable x holds 10 before parsing. Both parsed expressions use that value.

x = 10
println(eval(Meta.parse("x * 2")))
println(eval(Meta.parse("x + 5")))

Example

exprs = ["2 + 3", "4 * 5", "(10 - 2) / 4"]
for e in exprs
  println(eval(Meta.parse(e)))
end

Key points

  • Mini language: a mini language is a small set of text rules for writing arithmetic that a program can read and run.
  • Meta.parse: Meta.parse turns a text expression into an expression value.
  • Expression: an expression value holds the parts of a calculation in order.
  • Evaluation: evaluation runs an expression value and returns its plain result.
  • Precedence: the usual arithmetic order still applies inside a parsed expression.

In this example, a list holds three text expressions. The loop parses each one in turn and prints its evaluated result, so the three plain results appear in list order.

Note

a parsed expression is data first, and it only runs when it is evaluated.

Try it Yourself

Edit the code, then press Run.

Running is simulated · JuliaHub

Exercise

What does evaluating Meta.parse of 2 * 3 + 4 return?