Think Julia exercise 7-3

The built-in function Meta.parse takes a string and transforms it into an expression. This expression can be evaluated in Julia with the function Core.eval. For example:

julia> expr = Meta.parse("1+2*3")
:(1 + 2 * 3)
julia> eval(expr)
7
julia> expr = Meta.parse("sqrt(Ļ€)")
:(sqrt(Ļ€))
julia> eval(expr)
1.7724538509055159

Write a function called evalloop that iteratively prompts the user, takes the resulting input and evaluates it using eval, and prints the result. It should continue until the user enters done, and then return the value of the last expression it evaluated.

I only did this

function Evaloop()

    while true
        print("input: ")
        a=Meta.parse(readline())
        if typeof(a)==Symbol 
            break
        elseif a.head==:call
            println(eval(a))
        elseif error("input must be expression")
        end 
    end
end
Evaloop()

I couldnā€™t write code that stops by entering Done

How about:

julia> function evaloop()
           while true
               print("input: ")
               l = readline()
               if l=="done"
                   break
               end
               try
                   println(eval(Meta.parse(l)))
               catch e
                   println(e)
               end
           end
       end
1 Like