【问题标题】:Racket strange (require ...) semantics球拍奇怪的(需要...)语义
【发布时间】:2017-03-18 13:53:42
【问题描述】:

我有一个球拍代码:

#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

【问题讨论】:

    标签: racket rackunit


    【解决方案1】:

    发生错误是因为您在错误的命名空间中使用了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 上的文档,尤其是关于命名空间的部分。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-09-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-29
      相关资源
      最近更新 更多