【问题标题】:How to call function within a function to get price of a list?如何在函数中调用函数来获取列表的价格?
【发布时间】:2021-03-14 01:18:18
【问题描述】:

我是方案新手,我正在尝试创建一个函数,该函数使用另一个函数来获取列表的价格。 我有清单:

(define-struct store(id desc price))
(define master (list
   (make-store 1 'milk 2.50)
   (make-store 2 'meat 3.29)
   (make-store 3 'eggs 1.99)
   (make-store 4 'cereal 2.99)
   (make-store 5 'bread 2.79)
   (make-store 6 'soda 1.29)
   (make-store 7 'water 4.99)))

以及在该列表中查找元素的功能:

(define (lookup lst id)
  (cond ((null? lst) #f)
        ((= (store-id (car lst)) id)
         (list (store-id (car lst))
               (store-desc (car lst))
               (store-price (car lst))))
        (else (lookup (cdr lst) id))))

我将如何在另一个函数中调用此函数以单独打印价格?我认为如果不修改查找功能就不能这样做,我错了吗?有人可以帮我完成这个吗?

【问题讨论】:

    标签: scheme racket


    【解决方案1】:

    Lookup返回列表或#f,所以在获取价格之前,您需要检查返回的内容。不要修改您的代码,只需添加以下内容:

    (define (get-only-price id)
      (let ((found (lookup master id)))
        (if found (third found) #f)))
    
    (get-only-price 3)
    (get-only-price 10)
    

    【讨论】:

      【解决方案2】:

      既然可以返回对象,为什么还要改变返回列表的方式:

      (define (lookup lst id)
        (cond ((null? lst) #f)
              ((= (store-id (car lst)) id) (car lst))
              (else (lookup (cdr lst) id))))
      

      store 是一个实际的销售项目,所以我猜这个名字有点不对劲。在函数中,您可以通过这种方式获取价格:

      (define (product-price id)
        (let ((item (lookup master id)))
          (and item (store-price item))))
      

      如果找不到 id,这也将返回 #f。如果您确定它存在(或希望它在不存在时失败),您可以这样做:

      (store-price (lookup master id))
      

      【讨论】:

        猜你喜欢
        • 2021-12-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-07-01
        • 1970-01-01
        • 2022-09-29
        相关资源
        最近更新 更多