返回Scheme中列表中的最小项

时间:2017-04-15 19:09:41

标签: list recursion scheme

注意:我这样做是为了完成家庭作业。我不是在寻找算法来解决我的问题,只是想了解Scheme的工作原理。

我是计划新手并尝试编写一个小程序来查找列表中的最小项目。该程序正在工作,因为它找到了正确的答案(所以逻辑有点健全),但我只知道这一点,因为它出现了一个错误,它试图将我的答案视为一个函数和调用它

(DEFINE (startmin mylist)
(

    (repeatmin (CAR mylist) (CDR mylist))


))


(DEFINE (repeatmin curmin mylist)
(

    (IF (NULL? mylist) ;If the list is empty

        ;This is where I'm at a loss. I want a way for this value to be
        ;sent out once the list is empty
        curmin ;return the current minimum

        (IF (< curmin (CAR mylist)) ;if the current minimum is less than the head of the list
            (repeatmin curmin (CDR mylist)) ;recurse with curmin
            (repeatmin (CAR mylist) (CDR mylist)) ;otherwise recurse with the head of the list.
        )
    )
))

我真的不知道如何找到值,一旦找到,退出递归,因为它一直试图将值视为一个函数。

1 个答案:

答案 0 :(得分:2)

你的括号已关闭。如果你写

((if ...))

这意味着if的结果是一个函数,一旦值被cmoputed立即调用。看起来你正在使用括号,好像它们是块一样,比如C中的{},但它们不是。实际上(begin ...)是Scheme中的一个块。当然,一个函数,letcond项隐含开始。因此

(define (func . args)
  (begin 
    x
    y))

相同
(define (func . args)
  x
  y)

另请format your code correctly。缩进可帮助您阅读代码和嵌套。我真的不注意括号,只关注至关重要的位置。选择一个为您执行此操作的编辑器。例如。我使用DrRacket是一个很好的。

相关问题