Iterative filtering odd numbers in list - list

Here is a task I have to solve: Write an iterative function, that receives a list with numbers and creates a new list, which only consists of the even numbers from the received list.
I even found a few posts with similar questions and solutions, but I couldn't use them as help, because in these solution they were using the "car" and "cdr" commands, which we haven't had in our schedule yet. How can do this? I would start like this:
(define filter-odds
(lambda(x)
(if (odd? x)
...)

Terrible oversight: no one has mentioned How To Design Programs, here. This kind of program is right smack in the middle of HtDP's path. Specifically, this is a totally straightforward application of the List template from section 9.3, "Programming with Lists." Perhaps your class is already using HtDP?

Well, in the absence of car ⁄ cdr accessors, your only other choice is using reduce from SRFI1:
(define filter-odds
(lambda (lst)
(reduce-right
(lambda (e ; list's element
acc) ; accumulated results from the right
(if (odd? e)
.... ; combine e and the results-so-far
.... )) ; ignore e
'()
lst )))
But, right reduce most likely won't be iterative. Left reduce usually is. It will build the result in reverse order though, but you can reverse a list iteratively in another pass, using the same approach, without filtering at all (i.e. using the test procedure which always succeeds).
With the first ⁄ rest accessors available though, all you need to do is to write down the implementation for reduce yourself, then fuse it into the definitions above:
(define reduce
(lambda (f acc ls)
(if (null? ls)
acc
(reduce f (f acc (first ls)) .....))))
In other words, just follow the above code skeleton and add replace the call to f with some checks for odd? or something, to get the filter-odd?-reversed; then figure out the f to use so as to define the reverse-list function.

Related

Subset / Subsequence Recursive Procedure in Simply Scheme Lisp

I am working my way through Simply Scheme in combination with the Summer 2011 CS3 Course from Berkley. I am struggling with my understanding of the subset / subsequence procedures. I understand the basic mechanics once I'm presented with the solution code, but am struggling to grasp the concepts enough to come up with the solution on my own.
Could anyone point me in the direction of something that might help me understand it a little bit better? Or maybe explain it differently themselves?
This is the basis of what I understand so far:
So, in the following procedure, the subsequences recursive call that is an argument to prepend, is breaking down the word to its basest element, and prepend is adding the first of the word to each of those elements.
; using words and sentences
(define (subsequences wd)
(if (empty? wd)
(se "")
(se (subsequences (bf wd))
(prepend (first wd)
(subsequences (bf wd))))))
(define (prepend l wd)
(every (lambda (w) (word l w))
wd))
; using lists
(define (subsequences ls)
(if (null? ls)
(list '())
(let ((next (subsequences (cdr ls))))
(append (map (lambda (x) (cons (car ls) x))
next)
next))))
So the first one, when (subsequences 'word) is entered, would return:
("" d r rd o od or ord w wd wr wrd wo wod wor word)
The second one, when (subsequences '(1 2 3)) is entered, would return:
((1 2 3) (1 2) (1 3) (1) (2 3) (2) (3) ())
So, as I said, this code works. I understand each of the parts of the code individually and, for the most part, how they work with each other. The nested recursive call is what is giving me the trouble. I just don't completely understand it well enough to write such code on my own. Anything that might be able to help me understand it would be greatly appreciated. I think I just need a new perspective to wrap my head around it.
Thanks in advance for anyone willing to point me in the right direction.
EDIT:
So the first comment asked me to try and explain a little more about what I understand so far. Here it goes:
For the words / sentence procedure, I think that it's breaking the variable down to it's "basest" case (so to speak) via the recursive call that appears second.
Then it's essentially building on the basest case, by prepending.
I don't really understand why the recursive call that appears first needs to be there then.
In the lists one, when I was writing it on my own I got this:
(define (subseq lst)
(if (null? lst)
'()
(append (subseq (cdr lst))
(prepend (car lst)
(subseq (cdr lst))))))
(define (prepend i lst)
(map (lambda (itm) (cons i itm))
lst))
With the correct solution it looks to me like the car of the list would just drop off and not be accounted for, but obviously that's not the case. I'm not grasping how the two recursive calls are working together.
Your alternate solution is mostly good, but you've made the same mistake many people make when implementing this (power-set of a list) function for the first time: your base case is wrong.
How many ways are there to choose a subset of 0 or more items from a 0-element list? "0" may feel obvious, but in fact there is one way: choose none of the items. So instead of returning the empty list (meaning "there are no ways it can be done"), you should return (list '()) (meaning, "a list of one way to do it, which is to choose no elements"). Equivalently you could return '(()), which is the same as (list '()) - I don't know good Scheme style, so I'll leave that to you.
Once you've made that change, your solution works, demonstrating that you do in fact understand the recursion after all!
As to explaining the solution that was provided to you, I don't quite see what you think would happen to the car of the list. It's actually very nearly the exact same algorithm as the one you wrote yourself: to see how close it is, inline your definition of prepend (that is, substitute its body into your subsequences function). Then expand the let binding from the provided solution, substituting its body in the two places it appears. Finally, if you want, you can swap the order of the arguments to append - or not; it doesn't matter much. At this point, it's the same function you wrote.
Recursion is a tool which is there to help us, to make programming easier.
A recursive approach doesn't try to solve the whole problem at once. It says, what if we already had the solution code? Then we could apply it to any similar smaller part of the original problem, and get the solution for it back. Then all we'd have to do is re-combine the leftover "shell" which contained that smaller self-similar part, with the result for that smaller part; and that way we'd get our full solution for the full problem!
So if we can identify that recursive structure in our data; if we can take it apart like a Russian "matryoshka" doll which contains its own smaller copy inside its shell (which too contains the smaller copies of self inside itself, all the way down) and can put it back; then all we need to do to transform the whole "doll" is to transform the nested "matryoshka" doll contained in it (with all the nested dolls inside -- we don't care how many levels deep!) by applying to it that recursive procedure which we are seeking to create, and simply put back the result:
solution( shell <+> core ) == shell {+} solution( core )
;; -------------- ----
The two +s on the two sides of the equation are different, because the transformed doll might not be a doll at all! (also, the <+> on the left is deconstructing a given datum, while {+} on the right constructs the overall result.)
This is the recursion scheme used in your functions.
Some problems are better fit for other recursion schemes, e.g. various sorts, Voronoi diagrams, etc. are better done with divide-and-conquer:
solution( part1 <+> part2 ) == solution( part1 ) {+} solution( part2 )
;; --------------- ----- -----
As for the two -- or one -- recursive calls, since this is mathematically a function, the result of calling it with the same argument is always the same. There's no semantic difference, only an operational one.
Sometimes we prefer to calculate a result and keep it in memory for further reuse; sometimes we prefer to recalculate it every time it's needed. It does not matter as far as the end result is concerned -- the same result will be calculated, the only difference being the consumed memory and / or the time it will take to produce that result.

Recursively adding to a list using Scheme

I'm brand new to functional programming, and relatively new to programming as a whole. So I'm pretty lost trying to understand the syntax of Scheme. But this is a pretty simple question. I'm trying to create a function that recursively fills and prints a list from numbers x to y. Between recursion and this being a new language for me, I'm quite stuck.
(define (gen-list x y)
(if (> start end)
'()
(append '() (gen-list ((+ 1 x) y)) ) ))
If I were to enter in (gen-list 1 5) I would expect the result to be 1 2 3 4 5. This is currently giving me an error of "application: not a procedure" when it tries to call itself again. I have gotten around the error, but not been able to print anything remotely like what I'd like to. Any help is appreciated.
You have a couple of errors:
The parameters are called x and y, but you refer to them as start and end (I'd suggest to use start and end instead, they make the code easier to understand.)
You have more parentheses than needed in the last line. This is very important and an endless source of confusion for beginners. Don't surround all expressions with () unless you want to call a procedure.
We recursively build new lists with cons, append is for concatenating existing lists.
You're not actually using start, which is the current element in the recursion, to build the new list - you're just appending empty lists.
A list is an element consed to another list, or the empty list '(). That's why we return '() in the base case. For example, this is how a two-element list looks like: (cons 1 (cons 2 '())).
With all said and done, this is the proper way to build our list:
(define (gen-list start end)
(if (> start end)
'()
(cons start
(gen-list (+ start 1) end))))
As a final comment: the above procedure already exists in Racket, you don't need to rewrite it. Read about range in the documentation.
One of the problems with the 'obvious' answer to this question is that it doesn't really work very well. Consider this:
(define (gen-list start end)
(if (> start end)
'()
(cons start
(gen-list (+ start 1) end))))
Well, if start is much less than end there are going to be a huge number of recursive calls on the stack, because this is a properly recursive function: the recursive call to gen-list is a real call and has to return before the call to cons (which is a tail call) can happen.
The way to deal with this is to turn patterns which look like (cons x (<recursive-call> ...)) into patterns which look like (<tail-call> ... (cons x ...)): you need a function with an extra argument, an accumulator. This means that the calls which were previously recursive are now tail calls and everything is therefore good: the process is now iterative.
The problem with this is that lists come out backwards (you need to think about why this is, but it's obvious after a bit of thought). So you then need to reverse the result. Fortunately reversing a list is also an iterative process, so that's OK.
But in this case, well, you can just count backwards! So a simple-minded approach looks like this, using a locally-defined auxiliary function (this can be defined as a top-level function, but why bother?):
(define (gen-list low high)
(define (gla i result)
(if (< i low)
result
(gla (- i 1) (cons i result))))
(gla high '()))
You can see this is counting backwards: the initial call to gla starts with high & then constructs the list backwards. So, now:
> (gen-list 1 3)
'(1 2 3)
As we want.
This is such a common pattern in Scheme that there is a special construct for it: named let. So we can rewrite the above more idiomatically as:
(define (gen-list low high)
(let gla ([i high] [result '()])
(if (< i low)
result
(gla (- i 1) (cons i result)))))
This is exactly the same as the previous answer: it just moves the initial call to the top and combines it with the local definition of gla. This is probably the idiomatic Scheme way to do something like this (although people who write more Scheme than me might differ: I'm really a CL person and have inevitably poor taste).
This is where the story should end, but I can't resist adding the following. In the bad old days of comp.lang.lisp, people used to ask obvious homework questions and since there was no karma system one approach was to give an answer which solved the problem ... while being absurdly opaque.
So first of all we can turn gla into a function which gets passed a continuation to call rather than knowing it must call itself:
(define (gen-list low high)
(let ([gla (λ (cont i result)
(if (< i low)
result
(cont cont (- i 1) (cons i result))))])
(gla gla high '())))
And then, of course we can turn (let ([x y]) ...) into ((λ (x) ...) y):
(define (gen-list low high)
((λ (gla)
(gla gla high '()))
(λ (cont i result)
(if (< i low)
result
(cont cont (- i 1) (cons i result))))))
And that's a nice, pure answer ... which no student would ever come up with.
An alternative approach which is even more malicious is just to explicitly use the Y combinator, of course.
Just adding tail call recursive version
(define (gen-list start end (acc '()) #:step (step 1))
(cond ((> start end) (reverse acc))
(else (gen-list (+ start step) end (cons start acc)))))
Personally I love cond because you have all the conditions then below each other (or an else) - this is the style of The little Schemer a very good book for learning recursive thinking.
You need more than just the (> start end) base case, you also need a (= start end) base case in which you return (list start)

if statement in lambda Scheme

I'm a new schemer. I just want to ask if I can include if-statements in a lambda? For example, (lambda (x) (if e1 e2 e3)). I don't see why not, but my program just keep failing if I write this way.
Thanks a lot!
Here's my code here.I'm trying to implement filter with higher-order functions as an exercise. Since #sepp2k has answered that it's totally fine to include ifs in lambda, I'd guess it's the problem of my use of foldr?
If anyone can give some insight into this to help me understand the way it works, I'd really appreciate it!
(define filter (f xs)
(if (null? xs) '()
(foldr (lambda (elem ys) ((if (f elem) (cons elem ys)
(cons '() ys)))) '() xs)))
Of course we can use an if inside a lambda, in fact, any valid expression can go inside a lambda. There are more serious errors in your code:
There are additional (and unnecessary) parentheses surrounding the innermost if expression. Scheme will interpret them as a function application, and that's not what you want to do here
The else of the if expression is wrong, you just have to pass the accumulator without modifications
The function definition is incorrect
Also the whole function can be simplified, there's no need for the outermost if and the indentation can be improved. Try this:
(define (filter f xs)
(foldr (lambda (elem ys)
(if (f elem) ; if the predicate is true
(cons elem ys) ; then `cons` element to accumulator
ys)) ; otherwise leave accumulator alone
'()
xs))
It works as expected:
(filter even? '(1 2 3 4 5 6))
=> '(2 4 6)
Yes, it is perfectly valid to use ifs inside lambdas. If your program fails that must be because of other reasons.
Extra parens around the call to if. Scheme overloads grouping (list of expressions) and function-calls (+ 2 2).
FWIW, you might also use foldl, as foldr takes up O(|elements of the input|) memory.
Going deeper, lambdas are what's called a "special form" in scheme. That means that they obey different evaluation rules. I only bring this up because it gives some insight into a key feature of scheme: everything is just a form. define? Special form. lambda? Special form. Nothing you couldn't write yourself if you really felt like it. That means that with a lot of special forms, even if they seem automagic/baked-in, they don't have any esoteric caveats lying around.
Also, just for future reference, here are a couple of gems for your scheming: MIT Scheme Reference (lambdas), Racket Guide (Pairs and Lists)

Racket Sum of Perfect Roots Implementation

I am trying to write a Racket function that takes in a list of numbers as the input, and outputs the sum of the square roots of those numbers in the list that are perfect squares. The code I have currently does not compile, and is as follows:
(define (sum-of-perfect-roots lst)
(apply + (map (lambda (number)
(sqrt number)) (filter (exact? sqrt(number)) lst))))
I know that my error lies in the usage of the predicate for the filter function. I don't know how to return the list of only perfect squares correctly. Any help is appreciated!
Racket actually has a built-in math library, and the math/number-theory module provides a convenient perfect-square function. The documentation for perfect-square describes it as follows:
Returns (sqrt m) if m is perfect square, otherwise #f.
This, of course, makes implementing your function trivial. You could just do something like this:
(require math/number-theory)
(define (sum-of-perfect-roots lst)
(apply + (filter-map perfect-square lst)))
Using filter-map is also more efficient, since it doesn't need to build the list twice. Still, if you'd rather roll your own implementation for learning purposes, reimplementing perfect-square would not be terribly difficult.
(define (perfect-square n)
(define root (sqrt n))
(if (integer? root) root #f))
If you wanted to make it more efficient, you could avoid building the intermediate list entirely by using fold. Racket's for/sum comprehension form makes this easy to implement.
(define (sum-of-perfect-roots lst)
(for/sum ([n (in-list lst)])
(or (perfect-square n) 0)))

Racket - output content of a list

I have defined a list (in Racket/Scheme):
(define myList (cons 'data1 (cons 'data2 (cons 'data3 (cons 'data4 empty)))))
or
(list 'data1 'data2 'data3 'data4)
And I want to write a function that cycles through the list and outputs all values of the list.
(define (outputListData list)
(cond
[(null? list) list]
[else (getListData)]))
With what function can I cycle through the content of the list? I know one can use first & rest to get list data, but I guess that's not the right way here.
BTW: Is there a good, compact racket reference like php.net? I find the official Racket docs very confusing ...
You can use a for loop. Example:
(for ([x (list 1 2 3)])
(printf "~s -> ~s\n" x (* x x)))
There are more functional ways to do this, of course, but this way works too. You'll probably want to look at a textbook like How To Design Programs to do the recursive approach. See: http://www.ccs.neu.edu/home/matthias/HtDP2e/
dyoo's solution is nice and succinct in a Scheme like Racket that has useful iteration routines built in. Just FYI, though, your 'outputListData' is not far from being the standard recursive way to do this. You just need to change a couple of lines:
(define (outputListData list)
(cond
[(null? list) #f] ; actually doesn't really matter what we return
[else (printf "~s\n" (first list)) ; display the first item ...
(outputListData (rest list))])) ; and start over with the rest
Since this is an "imperative" kind of procedure that isn't designed to return a value, it doesn't really matter what we do with an empty list so long as we stop recurring (to avoid an infinite loop). If the list isn't empty, we output the first element and start over recursively with the rest of the list.
BTW, here's another way you could write something almost identical if you just needed a "for" loop in the middle of some other function:
(let loop ((l (list 'foo 'bar 'baz 'quux))) ; or put whatever input you need
(cond ((null? l) #f)
(else
(printf "~s\n" (first l))
(loop (rest l)))))
One way to think about this "named let" is that it defines a temporary function called loop, which works just like outputListData above. Scheme has the nice property that it won't grow the stack for "tail calls" like these, so you can always write what would be an "iterative" for or while loop in this recursive style.
I highly recommend The Little Schemer by Friedman and Felleisen for a quick intro to this style of function writing! I found it through Douglas Crockford's page here.
Edit as per comments: Use for-each
(for-each display myList)
Try this:
(void (map display myList))
Breaking it down:
(void x) causes x to be ignored instead of returned to the REPL/parent expression as a value.
(map function lst): For a list '(a1 a2 ... an) returns the list '((function a1) (function a2) ... (function an)).
So we use map to display all the items, but since we only care about the side-effect and not the return value, we call void on the returned list.
Official docs:
void
map
I think the solution that is the easiest to understand it to come up with a so called "list-eater" function. This is the way my university introduced recursion and lists in Racket. Also most books on Racket (i.e. "How To Design Programs" or "Realm Of Racket") explain it this way. This is the code:
(define my-list (list 'data1 'data2 'data3 'data4))
(define (print-list a-list-of-data)
(when (not (empty? a-list-of-data))
(print (first a-list-of-data))
(print-list (rest a-list-of-data))))
If you call the function with the example list my-list, you will get the following output:
(print-list my-list)
'data1'data2'data3'data4
The function does the following: As long as the given list is not empty, it grabs the first element of that list and passes it to the function print. Then, it tells itself to do the exact same thing with the rest of the list. (It calls itself on the rest of the list.) This second part is what they call recursion.
However, you can shorten that by using a function called map:
(define (print-list a-list-of-data)
(map print a-list-of-data))
This basically says that you want the function print to be called on each element of the given list. The output is exactly the same.
Hope it helped!