计算向量的非零输入的函数

时间:2017-04-02 22:49:26

标签: scheme racket

我是计划新手并且难以理解计划中的向量。我需要创建一个函数来计算非零输入的数量 一个向量。我需要通过不将矢量转换为列表来实现这一点。 例如。

(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)) 我该如何解决这个错误?

1 个答案:

答案 0 :(得分: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

需要考虑的一些事项:

  • 跟踪您的括号。例如,(zero? vector-ref vector position)应为(zero? (vector-ref vector position)),其中zero?的arity为1,vector-ref的arity为2。与do ...(do ...
  • 类似
  • if语句必须具有 else 子句(即(if condition then else))。例如,(if true 1)会失败,但(if true 1 2)会通过。因此,(if ((not (zero? vector-ref vector position))) (+ total 1))会失败。