返回基于最大字段的结构

时间:2014-12-14 00:05:41

标签: scheme lisp racket

我有一个结构列表。每个结构都是(make-struct STRING INT)。我想以递归方式遍历列表并返回具有最大INT字段的结构。

我该怎么做?作为一名24个月的程序员,这对我来说是最大的编码挑战之一。 Fyi,我尝试使用折叠,我尝试了局部变量(它给出了错误),内置函数,但没有任何效果。

我需要逻辑......所以沮丧地盯着我的屏幕看了2个小时。

3 个答案:

答案 0 :(得分:2)

foldr的问题是基本情况(你如何处理空列表?)。这是一个天真的解决方案:

(foldr (lambda (x y)
         (if (> (struct-int x)
                (struct-int y))
             x
             y))
       (first list-of-structs)
       (rest  list-of-structs))

在这种情况下,我们的“累加器”y跟踪具有最大int字段的结构。每个x都是列表中的x。它将x中的int与y中的int进行比较,并保留最大的结构。

答案 1 :(得分:2)

在Racket中,使用任意键很容易找到最大值,只需使用argmax - 这是惯用的解决方案,应该首选使用foldlfoldr。例如:

; replace `my-struct` `string` and `int` with the real names you're using
(struct my-struct (string int))

(define lst
  (list
   (my-struct "two" 2)
   (my-struct "three" 3)
   (my-struct "one" 1)))

; replace `my-struct-int` with the real accessor for the `int` field
(define the-max (argmax my-struct-int lst))
(my-struct-string the-max)
=> "three"

答案 2 :(得分:0)

假设您有一个数据类型my-struct,其中包含两个字段,一个字符串和一个整数:

(struct my-struct (s i))

现在,让我们列出一个包含该新类型实例的列表:

(define slst `(,(my-struct "one" 1) ,(my-struct "two" 3) ,(my-struct "three" 2)))

让我们使用foldl来获取具有整数字段最大值的实例:

(foldl (λ (s1 s2) (if (> (my-struct-i s1) (my-struct-i s2)) s1 s2))
       (car slst)
       (cdr slst)
 ))
相关问题