方案将列表定义为局部变量

scheme define list as local variable

我的目标是将列表定义为局部变量,以便从中获取最大元素。我的代码:

#lang racket
(define (f a b c)
    (list (+ (* a a) (* b b) (* c c)) (+ a c))
    (define (max-of-list-2 lst)
      (foldr max (first lst) (rest lst)))
  (max max_from_list 12))
(f 5 6 7)

在第二行中,我定义了带有计算值的列表。我的目标是将它传递到下一行以便从中获取最大数量,最后从列表的最大值和 12 中获取最大值。我做错了什么。如何处理?

您需要使用内部定义,如下所示:

(define (f a b c)
    (define max_from_list (list (+ (* a a) (* b b) (* c c)) (+ a c)))
    (define (max-of-list-2 lst)
      (foldr max (first lst) (rest lst)))
  (max max_from_list 12))

理解你的意图有点困难,但这是我能想到的最好的理解 -

(define (max a b)
  (if (< a b)
      b
      a))

(define (f a . more)
  (if (empty? more)
      (max a 12)
      (max a (apply f more))))

(f 5 6 7)
; => 12

(f 5 20 30)
; => 30

您可以在函数顶部使用 多个 define

你的意思是

(define (f a b c)
  (define lst (list (+ (* a a) (* b b) (* c c)) 
                    (+ a c)))
  (define (max-of-list-2 lst)
      (foldr max (first lst) (rest lst)))
  (max (max-of-list-2 lst) 12))

但这只相当于

(define (f a b c)
  (foldr max 12 (list (+ (* a a) (* b b) (* c c)) 
                      (+ a c))))