【问题标题】:Procedures on lists (scheme)清单程序(方案)
【发布时间】:2013-11-10 19:21:30
【问题描述】:

我正在编写一个程序,它返回一个包含所有负数和正数的列表 通过在原始过滤器过程中使用 lambda,甚至删除了整数(字符串可以保留)。我也避免使用递归,但这就是困扰我的地方。 到目前为止我所拥有的是:

(define (f2b lst)
    (cond ((null? lst)'()) ; if the list is empty, return the empty list
          ((pair? (car lst))  ; if the current element isn't a list   
              (filter (lambda (x) (or (even? x) (positive? x))) (car lst))
              (filter (lambda (x) (or (odd?  x) (negative? x))) (car lst))) 

 (else (string? (car lst))  ;otherwise, if the current element is a string,
            (car lst)       ; then return that element         
            (f2b (cdr lst))))) 

我也不确定如何同时应用这两个过滤程序。

【问题讨论】:

    标签: list scheme procedure


    【解决方案1】:

    比这更简单。您所要做的就是filter 列表。您只需要适当的谓词。

    你想什么时候保留一个元素?您根据要删除的内容来表达它,所以让我们从它开始。如果它是一个负奇数或一个正偶数,您想删除它,并保留其他所有内容。将其分解为更小的函数更容易。

    (define (positive-even? x) (and (positive? x) (even? x)))
    (define (negative-odd? x) (and (negative? x) (odd? x)))
    (define (remove-num? x) (or (positive-even? x) (negative-odd? x)))
    

    这定义了是否保留一个数字。但列表元素可能不是数字。所以我们 如果不是数字,或者不匹配remove-num?,请保留它:

    (define (keep-element? x) (or (not (number? x)) (not (remove-num? x))
    

    那么你的函数只需要调用过滤器:

    (define (f2b lst) (filter keep-element? lst))
    

    似乎有效:

    (f2b '(-4 -3 -2 -1 0 1 2 3 4 "a string" "another"))   
    => (-4 -2 0 1 3 "a string" "another")
    

    这是一个大型的功能:

    (define (f2b lst)
      (filter
       (lambda (x)
        (or (not (number? x)) 
            (not (or (and (positive? x) (even? x))
                     (and (negative? x) (odd? x))))))
       lst)
    

    就我个人而言,嵌套的or not or and 对我来说有点难以阅读...


    好的,显然你有嵌套列表。您在这里所要做的就是map filter 的结果,它具有以下功能:

    • 当给定一个列表时,返回(f2b lst)
    • 否则,原样返回元素。

    我会把它作为练习留给你,因为如果你认为我的函数可能在嵌套列表上工作,那么显然你还有很多学习要做......

    【讨论】:

    • 我尝试运行此代码,但它只是运行了我的测试用例并打印了整个列表。编辑:我应该澄清一下,我是通过嵌套列表运行它。
    • @user2789945:你运行了我给的最后一个函数?你给它的输入是什么?
    • 是的,它适用于常规列表,但是当我通过嵌套列表传递它时,它会打印整个列表。
    • @user2789945:哦,也许你应该提到你在问题中有嵌套列表?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-12
    • 2012-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多