2017-04-02 65 views
0

我是新来的方案,有困难的方案中的向量。我需要创建一个函数来计算向量中的非零输入的数量。我需要通过不将矢量转换为列表来做到这一点。例如 例如。计算矢量的非零输入的函数

(non-zero-dim #(3 0 2 4 0 2)) 
returns 4 

到目前为止我的代码是

(define non-zero-input 
(lambda (vector) 
(let ((size (vector-length vector))) 
    do ((position 0 (+ position 1)) 
     (total 0 
(if ((not (zero? vector-ref vector position))) 
(+ total 1)) 
(((= position size) total))))))) 

但是我得到这个错误:do: bad syntax in: (do ((position 0 (+ position 1)) (total 0 (if ((not (zero? vector-ref vector position))) (+ total 1)) (((= position size) total)) 如何解决这个问题?

回答

0

使用内置程序vector-lengthvector-filter-not,您可以简化功能:

(define (non-zero-dim vec) 
    (vector-length (vector-filter-not zero? vec))) 

例如,

> (non-zero-dim #(3 0 2 4 0 2)) 
4 

有些事情要考虑:

  • 跟踪o f你的括号。例如,(zero? vector-ref vector position)应该是(zero? (vector-ref vector position)),其中zero?的元数是1,而vector-ref的元数是2。同样与do ...(do ...
  • if声明必须其他条款(即(if condition then else))。例如,(if true 1)会失败,但(if true 1 2)会通过。因此,(if ((not (zero? vector-ref vector position))) (+ total 1))会失败。