Scheme中let表达式内dataInput变量未绑定的原因求解
错误原因
你用的let表达式是并行绑定变量的——所有绑定的表达式会在同一个环境里同时求值,raw-data的(read dataInput)在计算时,dataInput还没完成绑定,所以会触发未绑定错误。
let的特性就是每个绑定互相独立,后面的绑定不能引用前面刚定义的变量;如果需要顺序绑定、后一个绑定依赖前一个,得用let*。
另外,你定义imageList的时候多套了一层双引号,导致实际路径是带引号的字符串(比如"/home/perry/dir_image_search_list"),这会让file-exists?找不到正确的文件,需要去掉外层的引号。
修正后的代码
(define imageList "/home/perry/dir_image_search_list") ;text file of image exif data in a proper list (if (file-exists? imageList) (let* ((dataInput (open-input-file imageList)) (raw-data (read dataInput))) ;现在dataInput已经绑定,可以正常引用 (if (eof-object? raw-data) (begin (display "\"file is empty\"") (close-port dataInput) '() ) (begin (car raw-data) ;placeholder for future code to process the list (close-port dataInput) )) ) (begin (display "\"file not found\"") '() ) )
内容的提问来源于stack exchange,提问作者Trenton J
相关产品推荐
相关产品推荐

