Problems evaluating expressions from user input

I am trying to make a recursive definition that reads and executes custom expressions like (3 + 5) . Everything works, except for one problem with an arithmetic character.

I was able to reproduce the error in a simpler example:

 (define v '(1 + 3)) ((cadr v) 2 4) 

(cadr v) is a + character, but for some reason the procedure cannot be executed for the next two arguments. Did I miss something?

+4
source share
4 answers

I think since

 (cadr v) 

returns '+ not + (letter + not a function + ).

You need to evaluate it before applying it to the arguments.

This should work:

 ((eval (cadr v)) 2 4) ^evaluates the '+ to + 

edit This worked in racket interactively.

I'm not sure what the difference is, but made it work in r5rs mode in a racket (a script):

 #lang r5rs ;required by r5rs (define user-initial-environment (scheme-report-environment 5)) (define v '(1 + 2)) ;eval expects a quoted expression ;(it seems that if it a function it has to have arguments too) ;and evaluation environment. ((eval (cadr v) user-initial-environment) 2 4) 
+3
source

As others have pointed out, the problem is that the list you created contains the plus symbol, not the plus function.

Basically, for the same reason that '(a) returns a two-character list, rather than signaling an uncommitted identifier error; the citation begins the term in “data language”, where legal identifiers are interpreted as symbols, and not as references to variables.

The question, of course, is what you should do with it. Some of them suggested using "eval"; this is probably a bad idea, for the reasons why I think Matthew Flatt elegantly imprinted on his blog post .

Instead, you should probably write a simple mapping function. This is how I will write it. If you use my code in a task, be sure to write to me :).

 #lang racket ;; a mapping from symbols to operators (define operator-hash (hash '+ + '- - '* *)) ;; ... and whatever other operators you want. ;; example of using it: (hash-ref operator-hash '+) ;; ==> + 
+1
source

Try the following:

 (define v '(1 + 3)) (let ((operator (eval (cadr v))) (operand1 (car v)) (operand2 (caddr v))) (apply operator (list operand1 operand2))) 
0
source

You can do this with eval in Guile:

 (define (infix-eval v) (eval (list (cadr v)(car v)(caddr v)) (interaction-environment))) > (infix-eval '(1 + 2)) 3 

Instead of using interaction-environment , you can provide a different evaluation environment where you can also define some other characters not found in the standard schema so that expressions like (7 % 3) and (2 ^ 6) .

0
source

Source: https://habr.com/ru/post/1397282/


All Articles