问题
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:
- A function that returns a function taking a number as an argument and checks if the number is in the set.
- A union function that returns the set of all elements in arg1 or arg2
- Intersection function of above
- Function that returns elements in arg1 but not arg2
- 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