包含对的列表中的元素相乘 [英] Multiplying Elements in a List Containing Pairs

查看:187
本文介绍了包含对的列表中的元素相乘的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Scheme编写代码(函数):

I'm trying to write a code (function) using Scheme that:

  • 以任意大小的列表作为参数
  • 将列表中的每个数字相乘
  • 符号应跳过
  • 对中的值应包含在乘法中

换句话说,结果应该如下:

In other words, results should be as follows:

> (mult '(1 2 3))
6
> (mult '(1 2 x 3 4))
24
> (mult '(1 2 z (3 y 4)))
24 (mine gives me 2)

我的代码允许我跳过符号并乘以所有内容.但是,一旦我在列表中加入了一对,它就好像不是一个数字,因此就好像它不存在一样.这是我的代码:

My code allows me to skip over the symbols and multiply everything. However, once I include a pair inside the list, it acts as though it isn't a number, therefore acting like it doesn't exist. Here's my code:

(define mult
       (lambda (x)
               (if (null? x)
                      1
                      (if(number? (car x))
                         (* (car x) (mult (cdr x)))
                         (mult(cdr x))))))

我尝试在找到一个对时使用append,但是显然我做错了……非常感谢我提供有关如何将其包含在一对内的值的帮助.

I've tried to use append when it finds a pair, but clearly I did it wrong... Any help on how I could get it to include the values inside a pair would be much appreciated.

即'(1 2 y(3 z 4)= 1 * 2 * 3 * 4

i.e. '(1 2 y (3 z 4) = 1 * 2 * 3 * 4

推荐答案

您快到这里了,只是缺少列表了吗?测试:

You are nearly there, just missing the list? test:

(define (mult lst)
  (if (null? lst) 
      1
      (let ((ca (car lst)))
        (cond
          ((number? ca) (* ca (mult (cdr lst))))
          ((list? ca)   (* (mult ca) (mult (cdr lst))))
          (else         (mult (cdr lst)))))))

编辑

他是没有let的等效版本:

He're an equivalent version without let:

(define (mult lst)
  (cond
    ((null? lst)         1)
    ((number? (car lst)) (* (car lst) (mult (cdr lst))))
    ((cons? (car lst))   (* (mult (car lst)) (mult (cdr lst))))
    (else                (mult (cdr lst)))))

如您所见,(car lst)可能会被多次评估,因此我在第一个版本中使用let来避免这种情况.

As you see, (car lst) is likely to be evaluated more than once, so I used let in the first version to avoid this.

这篇关于包含对的列表中的元素相乘的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆