方案结构和清单 [英] scheme structures and lists
问题描述
(define-struct position (name numshares share-price))
(define p1
(cons (make-position "INT" 10 192) (cons (make-position "SSS" 4 42)
empty)))
mult
是我的辅助函数
(define (mult n)
( * (position-numshares n)
(position-share-price n)))
const在列表中获取position-numshares和position-share-price并将它们相乘.
const takes the position-numshares and the position-share-price in a list and multiplies them together.
(define (const n)
(cond
[(empty? n) empty]
[(cons? n)
(+ (mult (first n))
)]))
我想做的是获取列表的第一个,并将其余的列表加在一起.相反,我只获得列表的第一名.因此,如果我这样做(const p1),我只会得到1920,但是我想得到2088(10 * 192 + 4 * 42).我尝试重复进行其余的操作,但出现错误.我可能缺少一些简单的东西.帮助将不胜感激.
What I would like to do is take the first of the list and add the rest of the list together. Instead, I only get the first of the list. So if I do (const p1) I only get 1920, but I would like to get 2088 (10*192 + 4*42). I've tried recurring for the rest, but get an error. I am probably missing something simple. Help would be appreciated.
推荐答案
首先,请注意,一般而言,您可以
First, note that in general, you can do
(list a b)
代替
(cons a (cons b empty))
所以您用
(define p1
(list (make-position "INT" 10 192)
(make-position "SSS" 4 42)))
更易于阅读,使您的意图更清晰.现在,要从(make-position "INT" 10 192)
创建的结构中获取1920
,您已定义了辅助过程mult
.您可以map
mult
在列表p1
上以获取产品的新列表,即(1920 168)
.然后,您可以使用
which is easier to read, and makes your intent clearer. Now, to get 1920
from a structure created by (make-position "INT" 10 192)
, you've defined your helper procedure mult
. You can map
mult
over your list p1
to get a new list of the products, i.e., (1920 168)
. Then you can use foldl
with +
and 0
on that list to compute its sum.
(define (const lst)
(foldl + 0 (map mult lst)))
(const p1)
;=> 2088
如果您不想使用fold
和map
(这可能是合理的,因为map
意味着将分配一个新列表),则可以手动将其写出:
If you don't want to use fold
and map
(which might be reasonable, since map
means that a new list is getting allocated), you can write this out manually:
(define (const lst)
(let const ((sum 0) (lst lst)) ; pretty much an implementation of fold, but
(if (null? lst) ; with the function + built in, and mult applied
sum ; to each element before passing to +
(const (+ sum (mult (car lst)))
(cdr lst)))))
(const p1)
;=> 2088
另一种替代方法是使用foldl
,但不要传递+
,而是传递一个将+
和mult
组合在一起的函数:
Another alternative would be to use foldl
, but instead of passing +
, pass in a function that combines +
and mult
:
(define (const3 lst)
(foldl (lambda (struct sum)
(+ (mult struct) sum))
0
lst))
(const3 p1)
作为一个普通的Lisper,令我有些失望的是Scheme的foldl
过程在将函数应用到列表之前没有接受用于列表中每个元素的关键参数.在Common Lisp中,我们将(foldl
/foldr
是
As a Common Lisper, it's a bit disappointing to me that Scheme's foldl
procedure doesn't take a key argument that gets applied to each element of the list before the function is applied to it. In Common Lisp, we'd write (foldl
/foldr
are reduce
in Common Lisp):
(reduce '+ p1 :key 'mult)
这篇关于方案结构和清单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!