scheme - 了解序列的工作原理
问题描述
我有以下accumulate
功能:
; accumulate
(define (accumulate op initial sequence)
(if (null? sequence)
initial
(op (car sequence) (accumulate op initial (cdr sequence)))))
我正在尝试编写一个length
函数来使用该函数获取序列的长度accumulate
。
对于要插入的功能accumulate
,为什么用它(+ y 1)
代替(+ x 1)
?这是我无法弄清楚的部分:
(define (length sequence)
(accumulate (lambda (x y) (+ x 1)) ; wrong
0
sequence))
(define (length sequence)
(accumulate (lambda (x y) (+ y 1)) ; correct
0
sequence))
解决方案
你的问题是,x
并y
没有告诉你它是什么。但是,如果您查看,accumulate
您会看到如何op
调用:
(op (car sequence) ; first argument is the element
(accumulate op initial (cdr sequence))) ; second argument is the accumulated value
虽然它看起来并不像那样想象第二个参数正在调用accumulate
空序列。然后你得到这个:
(op (car sequence)
initial)
所以让我们制作length
:
(define (length sequence)
(accumulate (lambda (element initial)
;; initial is often also called acc / accumulator
(+ 1 initial))
0
sequence))
所以答案是第一个参数是单个元素,而第二个参数是0
初始0
值1
(因而有数。为什么你不使用第一个参数是你不能真正使用"a"
或列表包含的任何元素来计算元素,因为你只需要计算它们而不将它们用作值。如果您使用第一个参数并且它恰好是字符串,那么(+ "a" 0)
应该帮助找出列表有长度1
吗?
推荐阅读
- javascript - Vue 是否因为未知的隐藏字符而未显示在文件 #1 中?
- sparse-matrix - Amazon SageMaker kMeans 不会将稀疏矩阵 (csr_matrix) 作为输入,在使用密集矩阵之前还有其他选择吗?
- python-3.x - 我如何在 python 中搜索给定的句子并从该结果中获取最常用的单词?
- linux - du -hs 后如何按名称并排排序
- python - 在没有任何 Python 库的情况下,如何在 Python 中进行左和中操作?
- angularjs - angularjs中的逻辑容器
- python - Python - 球坐标有Z轴偏差
- apache - 将 phpmyadmin 安装到 VPS Ubuntu 16.04 时出现问题
- python - python - 登录页面并获取cookies
- python - Python在对列表中的数字进行排序时忽略零