Functional programming 方案功能:(显示到n';(4 6 3-8 3 4)5)=>;(4 3 -8 3 4)
我试图在Scheme中编写一个函数,它接受一个列表和一个整数,并输出相同的列表减去所有小于整数的成员。。。请帮忙。我似乎无法将数字添加到可以输出的新列表中Functional programming 方案功能:(显示到n';(4 6 3-8 3 4)5)=>;(4 3 -8 3 4),functional-programming,scheme,Functional Programming,Scheme,我试图在Scheme中编写一个函数,它接受一个列表和一个整数,并输出相同的列表减去所有小于整数的成员。。。请帮忙。我似乎无法将数字添加到可以输出的新列表中 (define result '()) (display result) (define nums-less-than-x (lambda (lst x) (define impl (lambda (l1 b result) (if (null? l1) result (b
(define result '())
(display result)
(define nums-less-than-x
(lambda (lst x)
(define impl
(lambda (l1 b result)
(if (null? l1) result
(begin (if (> b (car l1))
(begin (cons (car l1) result)
;(display result)(newline)(newline)
(display (car l1) )(newline))
)
(impl (cdr l1) b result)
))
))
(impl lst x result)
))
(display (show-up '(4 6 3 -8 3 4) 5))
代码juss在我运行时显示()
,一个类似这样的空列表
(display (num-less-than-x '(some list) x))
当以函数式编程时,我们尝试使用现有的过程来解决问题。考虑到这一点,首选的解决方案是:
(define (show-up-to-n lst x)
(filter (lambda (n) (< n x))
lst))
(定义(显示至n lst x)
(滤波器(λ(n)(
还请注意,在真正的功能代码中,我们不惜一切代价避免修改状态的过程(如
set!
),最好创建一个包含结果的新列表。您的结果永远不会更新。通常,我只希望当元素不是结果的一部分时,或者是递归时,如:
(impl (cdr l1) b (cons (car l1) result))
我注意到您将调试输出作为begin
中的最后一个表达式,例如
(begin
expression-that-does-something
(display ...)
(newline))
请注意,表达式结果不是结果,而是新行的结果,通常是一些未定义的值。您需要首先放置调试内容,然后将函数返回的表达式作为尾部。或者,您可以创建一个调试函数:
(define (debug expr)
(display expr)
(newline)
expr))
我的理解是,您希望过程返回结果,而不是显示结果,这是正确的方法:
(define show-up
(lambda (lst mx)
(if (null? lst)
lst
(let ((c (car lst)))
(if (> c mx)
(show-up (cdr lst) mx)
(cons c (show-up (cdr lst) mx)))))))
测试:
> (show-up '(4 6 3 -8 3 4) 5)
'(4 3 -8 3 4)
代码juss显示“()”,这是一个空列表,就像我运行(display(num-less-than-x'(some list)x))函数时一样。我认为您的意思是“减去大于整数的所有成员”。result
变量的用途是什么?你从不更新它。您是想写入(set!result(cons(car l1)result))
来添加元素吗?请注意impl
函数中的变量result
与全局变量不同。显示的是什么?这应该是nums-less-小于-x
?