English 中文(简体)
简易方案问题
原标题:easy scheme question
  • 时间:2011-05-21 19:03:00
  •  标签:
  • list
  • scheme

how can I find a list from given database?? Database:

(10 math phys)

(11 math chem)

(13 bio chem)

(15 geo phys)

我想实现time,它在列表中显示第一次和第二次考试。

>(time ’10)

(list ‘math ‘phys)

>(time ’19)

empty

我想实现secondExams,它返回第二次考试的时间。

>(secondExams ‘phys)

(list ‘10 ’15)

>(secondExams ‘chem)

(list ’11 ’13)

非常感谢。

最佳回答

首先,让我们澄清一下您的数据库格式。将其作为列表列表:

(define database
   ((10 math phys)
    (11 math chem)
    (13 bio chem)
    (15 geo phys)))

然后time只需要递归地遍历列表,并将子列表的第一个元素与目标值进行比较。如果没有找到匹配的值,我们将返回空列表。我们将在助手过程中执行此操作,以匹配您正在精确查找的功能。

(define time-ish
  (lambda (target lst)
    (cond ((null? lst) lst)
          ((eq? target (caar lst)) (cdar lst))
          (else
           (time-ish target (cdr lst))))))

(define (time lookin-for)
  (time-ish lookin-for database))

然后我们可以为第二次考试做一些非常类似的事情。不过这次我们将递归地构建一个匹配列表。

(define exam-helper
  (lambda (target lst)
    (cond ((null? lst) lst)
          ((eq? target (third (car lst))) (cons (first (car lst))
                                                (exam-helper target (cdr lst))))
          (else
           (exam-helper target (cdr lst))))))

(define (secondExams lookin-for)
  (exam-helper lookin-for database))

我还没有测试过这个代码,但我很确定它会对你有效。

问题回答

暂无回答




相关问题
Parsing with DCGs in Scheme (without Prolog)?

Lots of Prolog-in-Scheme implementations are out there. E.g. Kanren, Schelog. Apparently in "Paradigms of AI Programming" Norvig implements Prolog-to-Lisp compiler in Lisp in order to use Definite ...

Applying a symbol as a procedure

Suppose I have a simple symbol: > + + Is there any way I can apply that symbol as a procedure: > ((do-something-with +) 1 2) 3 So that + is evaluated to the procedure +?

string-split in DrScheme

How do I do equivalent of python s str.split in DrScheme? SRFI-13 doesn t seem to have it provided.

Scheme, getting the pointer from pointed struct

Assume I have a such struct: (define-struct node (value next)) ;and making 2 nodes, parent pointing to child as next. (define child (make-node 2 null)) (define parent (make-node 1 child)) Under ...

How to solve the following equation using accumulate (Scheme)

I m trying to do the following problem (there is a formula so I print-screened and uploaded it) Formula http://img248.imageshack.us/img248/6558/problemh.jpg (http://img248.imageshack.us/img248/6558/...

热门标签