enter code here
只需了解计划中偷看的基本知识。我试着看看球拍网站寻求帮助,但它并没有太大的帮助。或许我正在寻找错误的部分。无论如何,这一点如下。
我希望能够将x识别为char,然后继续窥视直到达到空间并将其重新定义为单词。然后为360做同样的事情。
任何提示? 谢谢,麻烦您了! :)
以下是我的代码在有帮助的情况下的样子
(define (work x)
(cond
((null? x)(write '$$))
(char-numeric? (car x))
(write 'Num)
(toke (cdr x)))
((char-alphabetic? (car x))
(write 'ID)
(work (cdr x)))
(else (write "other")))
这个问题是它会给我“xbox”的IDIDIDID(这对代码来说是有道理的)但是我想让它为整个单词xbox输出一次ID
答案 0 :(得分:1)
有更简单的方法可以解决问题,但它们涉及一些额外的语言知识。例如,使用regular expressions在空格处分割字符串,使用map
and filter
处理每个单词:
(define line "xbox 360")
(define (process line)
(map (lambda (word)
(cond ((string->number word) "number")
(else "word")))
(filter (lambda (str)
(not (equal? str "")))
(regexp-split #px"\\s+" line))))
请注意,收到的输入是一个字符串,在输入文件中包含一行(由过程file->lines
返回)。一般的想法是:逐行读取文件,并使用上面的代码片段依次处理每个文件。
如果你在代码中使用更高级的功能,那么上面就可以了。
编辑:
我只使用列表迭代和read-char
(不是peek-char
编写了一个版本,它只读取第一个字符并且没有前进到下一个字符),但是你会看到这是比上述程序要复杂得多:
(define (process line)
(let ((port (open-input-string line)))
(let loop ((char (read-char port))
(acc '()))
(cond ((eof-object? char)
(cond ((null? acc) '())
((string->number (list->string acc)) (list "number"))
(else (list "word"))))
((char-whitespace? char)
(cond ((null? acc)
(loop (read-char port) '()))
((string->number (list->string acc))
(cons "number" (loop (read-char port) '())))
(else
(cons "word" (loop (read-char port) '())))))
(else
(loop (read-char port) (cons char acc)))))))
两种解决方案都可以按预期进行以下测试:
(process "xbox 360")
> '("word" "number")
(process "1")
> '("number")
(process "a")
> '("word")
(process " ")
> '()
(process "")
> '()
(process " a b 1 a ")
> '("word" "word" "number" "word")