从字符串中移除元音(Scheme)

时间:2011-03-01 21:46:33

标签: scheme

我知道这个问题的基本算法,但我无法将句子更改为条件内的列表。我创建了make-list以使自己更容易,但我不确定将它放在代码中的哪个位置。例如,在第一个cond语句中,我需要将句子作为一个列表,然后检查句子中的第一个元素是否是元音..但我一直在做语法错误。

元音-Cl?如果一个字符是不区分大小写的元音,则返回#t,否则返回#f。

stenotype接受一个句子并在删除所有元音后返回它。

(define make-list
   (lambda (string)
     (string->list string)))

(define stenotype
  (lambda (sentence)
    (cond
      [(vowel-ci? (car sentence)) (stenotype (cdr sentence))]
      [else (cons (car sentence) (stenotype (cdr sentence)))])))

3 个答案:

答案 0 :(得分:2)

有一些不同的任务(准备输入,因此它可以由您的实现和处理本身处理),您已经分成两个不同的功能。下一步是组合功能,而不是重写后者以使用前者。组合函数的最简单方法是组合。撰写make-liststenotype(您可能希望将此作文命名),您将获得解决方案。

(define double
    (lambda (x) (* x 2)))

(define inc
    (lambda (x) (+ x 1)))

; one option: define a new function that's a composition    
(define double-inc
    (lambda (x) (inc (double x))))

; another option: compose the functions when you use them
(inc (double 23))

; yet another option: make the other functions local to the composition
; Useful if the other functions are subordinate to the composition, and 
; aren't useful outside of it. You often see this with recursive functions,
; where the outer function sets up a call to the recursive function
(define (double-inc x)
    (define (double x) (* x 2))
    (define (inc x) (+ x 1))
  (inc (double x)))

(define (max numbers)
    (define (max-recur maximum numbers)
      (cond ((eq? numbers '()) maximum)
            ((< maximum (car numbers)) (max-recur (car numbers) (cdr numbers)))
            (else (max-recur maximum (cdr numbers)))))
  (max-recur (car numbers) (cdr numbers)))

请注意,您在stenotype中缺少基本案例以结束递归。

答案 1 :(得分:2)

您只需将字符串转换为列表一次,并使用map或递归过滤掉元音。以下过程说明了如何使用map

(define (remove-vowels str) 
    (let ((res ()))
      (map (lambda (c) (if (not (vowel? c)) (set! res (append res (list c))))) 
           (string->list str))
      (list->string res)))

这是递归的,避免使用set!append

(define (remove-vowels str)
    (let loop ((slist (string->list str)) (res ()))
      (if (not (null? slist))
          (if (vowel-ci? (car slist))
              (loop (cdr slist) res)
              (loop (cdr slist) (cons (car slist) res)))
          (list->string (reverse res)))))

用法:

> (remove-vowels "hello, world")
"hll, wrld"
> (remove-vowels "goodbye cruel world")
"gdby crl wrld"

答案 2 :(得分:1)

(define make-list (string)

     (string->list string))

(cond
[(empty? make-list(sentence))empty]
      [(vowel-ci? (car make-list(sentence))) 
        (stenotype list->string ((cdr make-  list(sentence))))]
      [else (cons (car make-list(sentence)) (stenotype (cdr make-list(sentence))))])))