球拍奇怪(需要......)语义

时间:2017-03-18 13:53:43

标签: racket rackunit

我有一个球拍代码:

#lang racket
(provide (all-defined-out))

(struct weather (name perspective temperature humidity wind class) 
#:transparent)

;;Exercise 8
;;Todo implement
#;(define (read-examples file-name)
  (file->lines file-name))

;;todo uncomment
#;(define examples (read-examples "examples.txt"))

;;Exercise 9
(define (add-example examples example)
  (cons example examples))

;;Exercise 10
(define (attribute which examples)
  (define command (eval (string->symbol(string-append "weather-" 
(symbol->string which)))))
  (if (null? examples) null
      (cons (command (car examples)) (attribute which (cdr examples)))))

同样测试文件:

#lang racket
(require rackunit "xalt2.rkt")

(define examples (list (weather "Day1" 'cloudy -5 60 'yes '-)
                   (weather "Day2" 'cloudy 0 30 'no '+)
                   (weather "Day3" 'cloudy 10 45 'no '+)
                   (weather "Day4" 'cloudy 20 60 'yes '-)
                   (weather "Day5" 'cloudy 30 80 'no '+)))

;;tests for Exercise 9
(define argument-for-add-example (weather "Day77" 'cloudy 39 87 'no '+))
(define expected-result (cons argument-for-add-example examples))
(check-equal? (add-example examples argument-for-add-example) expected-result "addind to list is not working?")

;;tests for Exercise 10
(check-equal? (attribute 'wind examples) null "")

它给出了关于未定义结构函数的奇怪错误,但是我需要在测试文件中定义并使用结构的文件... 我确实使用了Racket 6.8

1 个答案:

答案 0 :(得分:4)

发生错误是因为您在错误的命名空间中使用eval

建议#1:Don't use eval.

考虑编写一个将属性符号转换为访问器的辅助函数:

;; get-attribute-function : Symbol -> (Weather -> Any)
(define (get-attribute-function attr)
  (case attr
    [(name) weather-name]
    ....))

或者您可以创建一个将符号映射到函数的哈希表。

建议2:如果必须,必须使用eval,您需要确保为其提供正确的命名空间。阅读reflection and dynamic evaluation上的文档,特别是关于命名空间的部分。