I am learning how to use higher-order functions in scheme. I get the idea of using higher-order functions, however I am having trouble using them. For this learning exercise, I would prefer to only use some combination of filter, fold, and/or map.
For example, I want to construct the set difference between two lists call them A and B. I am defining set difference as x such that x is an element of A but x is not an element of B. I only want to use the functions map, filter and fold. For example:
Let A = (1 8 6 2)
Let B = (5 7 9 1 6)
The set difference of A and B would be (8 2)
The idea is to construct a new list by iterating over the elements of A and seeing if an element of A equals an element of B, if so don’t add a to the new list; otherwise add a to the new list.
My algorithm idea goes something like this:
Let neq be “not equal to”
-
For each a in A and b in B evaluate the expression:
(neq? a b)For a = 1 we have:
(and (neq? 1 5) (neq? 1 7) (neq? 1 9) (neq? 1 1) (neq ? 1 6))
-
If this expression is true then a goes in the new list; otherwise don’t add a to the new list. In our example
(neq? 1 1)evaluates to false and so we do not add 1 to the new list.
Pretty much my entire procedure relies on 1, and this is where I have a trouble.
- How do I do step 1?
- I see that in step 1 I need some combination of the
mapandfoldfunctions, but how do I get theand a neq bdistributed?
EDIT This is the closest sample I have:
(fold-right (trace-lambda buggy (a b c) (and (neq? a b))) #t A B)
|(buggy 3 5 #t)
|#t
|(buggy 2 4 #t)
|#t
|(buggy 1 1 #t)
|#f
#f
The above shows a trace of my anonymous function attempting to perform the (and (neq? a b)) chain. However, it only performs this on elements in A and B at the same position/index.
All help is greatly appreciated!
A simplified version of
memberis easy to implement usingfold, of course:Now, with that, the rest is trivial:
If you want to amalgamate all that into one function (using your
neq?), you can do: