representing sets with lambda functions

和自甴很熟 提交于 2019-12-22 17:47:08

问题


I am struggling with understanding what I really need to do, and would like some outside input or a point to a good reference. I have been asked to use procedural representation to "implement sets of numbers." Each set will be a one argument function that takes a number and decides if the number is in the set. A few functions (that I have read can be defined in one line) that I have to create:

  1. A function that returns a function taking a number as an argument and checks if the number is in the set.
  2. A union function that returns the set of all elements in arg1 or arg2
  3. Intersection function of above
  4. Function that returns elements in arg1 but not arg2
  5. etc.

Now I know this is simply enclosing a lambda function, but I guess I am confused on how to represent a set and check it within the lambda function? If someone could point me in the right direction I would appreciate it.


回答1:


You have to realise that the first function in your TODO list is the constructor. The rest falls out from there I think.

(define (make-set x) (lambda (y) (eq? x y)))
(define (union x y) (lambda (z) (or (x z) (y z))))
(define (intersection x y) (lambda (z) (and (x z) (y z))))
(define (difference x y) (lambda (z) (and (x z) (not (y z)))))

(define set-5 (make-set 5))
(set-5 4)
(set-5 5)

(define set-45 (union (make-set 4) (make-set 5)))
(set-45 3)
(set-45 5)

(define set-34 (union (make-set 3) (make-set 4)))

(define set-4 (intersection set-34 set-45))
(set-4 3)
(set-4 5)
(set-4 4)

(define set-3 (difference set-34 set-45))
(set-3 4)
(set-3 5)
(set-3 3)


来源:https://stackoverflow.com/questions/19129413/representing-sets-with-lambda-functions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!