我一直在尝试创建一个子集?,成员?和交集函数,使用预定义的过滤函数和 map 函数的一些变体(ormap、andmap)。
“成员?”函数应该检查一个元素是否是列表的成员:
(define member?
(lambda (e s)
(ormap (curry same-elem? e) s)))
它正在使用一个名为“same-elem?”的函数。看起来像这样:
(define same-elem?
(lambda (e1 e2)
(cond ((and (set? e1) (set? e2)) (same-set? e1 e2))
((and (number? e1) (number? e2)) (= e1 e2))
(else (equal? e1 e2)))))
“子集?”检查一个集合中的元素是否是另一集合的一部分:
(define subset?
(lambda (s2 s1)
(andmap (curry member? s2) s1)))
“交集”函数应该返回两个集合的交集:
(define intersection
(lambda (s2 s1)
(filter (curry member? s2) s1)))
我使用“curry”函数的原因是因为我尝试遵循此 stackoverflow 线程中的解决方案:Scheme/Racket filter/map multiple arguments试图将第二个参数传递到我调用的函数中。但它不起作用。
每当我调用这些函数中的任何一个时,它都会输出一个错误,指出它需要在我的成员中的 ormap 调用中包含一个列表?函数但得到了一个元素。奇怪的是我的成员(member)?功能运行良好,直到几分钟前...我什至没有碰过任何东西!
我是编程新手,对Scheme完全陌生。如果映射/过滤器中的被调用函数只有一个参数,我知道如何使用映射/过滤器函数...但是如果我有多个参数,我该如何处理?请帮忙。
编辑:我在下面选择的解决方案不适用于 curry 。但是,如果您删除柯里函数并编写匿名函数,它确实可以工作。
像这样:
(define member?
(lambda (e s)
(ormap (lambda (x)
(same-elem? e x)) s)))
最佳答案
您的方法是正确的,您只需注意参数的顺序 - 例如,member?
应该接收一个集合作为其第一个参数,如果您打算对其进行柯里化(Currying),因为 andmap
会将单个元素传递给生成的 lambda
形式。另外,请注意,使用的高阶过程期望列表作为参数,而不是内置set
数据类型的实际集。这就是我的意思:
; tests if `e` is a member of `s`
(define member?
(lambda (s e)
(ormap (curry same-elem? e) s)))
; tests if `s1` is a subset of `s2`
(define subset?
(lambda (s1 s2)
(andmap (curry member? s2) s1)))
; finds the intersection of `s1` and `s2`
(define intersection
(lambda (s1 s2)
(filter (curry member? s1) s2)))
它们按预期工作:
(member? '(a b c d e) 'c)
=> #t
(subset? '(c d) '(a b c d e))
=> #t
(intersection '(c d b a) '(a x y b))
=> '(a b)
关于filter - 方案 - 如果 'map/filter' 中的函数有多个参数,如何使用它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40471125/