scheme recursive function list overrides - list

I'm trying to do a recursive function that gets a list of string-int pairs + a string named prefix, and using function named "starts-with" it sums up all the ints whose begininng match the prefix.
Problem is, I can never get the list to go forward, it gets stuck at the beginning and then program crashes.
(define (sum-of-pairs-start-with prefix ls)
( let*( (prefix2 (string->list prefix))
(str2 (string->list (car (car ls)))))
(cond((null? str2) 0)
( (starts-with prefix (car(car ls)))
(+ cdr(car ls) (sum-of-pairs-start-with prefix (cdr ls))) )
(else sum-of-pairs-start-with prefix (cdr ls))) ) )
I work with input:
(sum-of-pairs-start-with "a" (list (cons "a" 1) (cons "b" 2) (cons "aa" 33) (cons "ca" 4))) ;; =34
but once i get to the second pair in the list ("b" 2) it goes to the else condition as expected, but then ls gets back up one line to origin (with the previous value) instead of going forward to next value ("aa" 33).
I 'm new to scheme and I dont get why that happens, it's frustrating

You just have to call the starts-with procedure that we previously defined (let it take care of converting the strings to char lists), and fix all of the syntax problems:
(define (sum-of-pairs-start-with prefix ls)
(cond ((null? ls) 0)
((starts-with prefix (car (car ls)))
(+ (cdr (car ls)) (sum-of-pairs-start-with prefix (cdr ls))))
(else (sum-of-pairs-start-with prefix (cdr ls)))))
Once again, you're having trouble invoking the procedures. For example, these snippets are wrong:
cdr(car ls)
(else sum-of-pairs-start-with prefix (cdr ls))
Please, grab a book on Scheme and practice the basic syntax, remember that procedures are not called like this: f(x), the correct way is (f x). Also, pay attention to the correct way to indent the code, it'll be easier to find the errors if you follow the conventions.

Following is a solution using higher functions:
(define (sum-of-pairs-start-with prefix ls)
(apply +
(map cdr
(filter (λ (x) (starts-with prefix (car x)))
ls))))
It filters out those sublists which have prefix in first item, then gets second item (cdr) from each of those sublists and finally applies add function to all of them.

Related

Scheme - list passed into function returning empty

I am trying to define a helper function that takes an integer and a list as parameters and produces cartesian product of the integer and the list.
I believe I have the logic figured out. But when I test my code and pass a list into the function, the function returns an empty list.
(define (helper element set)
(cond
((null? set) '())
(cons '(element (car set)) (helper element (cdr set)))
)
)
For example, when I run (helper 5 '(6 8 9)) it returns an empty list.
I can't figure out why, but I think it has something to do with passing an integer with a list as parameters but I can't find anything to confirm this.
You have the wrong syntax for cond. The format is
(cond (test1 then1)
(test2 then2)
...)
There is no special allowance that the last case doesn't need a test. So when you write
(cond
((null? set) '())
(cons '(element (car set))
(helper element (cdr set))))
your test is the symbol cons, and your then-expression is "evaluate '(element (car set)), throwing the result away, and then evaluate and return (helper element (cdr set))" (there is an implicit begin around the expressions in the then part of a cond). Thus, helper always just recurses down to an empty set eventually, and then returns it, making no changes to it.
What you meant to do instead was use something that's always true as your last test, and then use the cons form as the body. Traditionally else is used for this, although #t is also fine:
(define (helper element set)
(cond
((null? set) '())
(else (cons '(element (car set))
(helper element (cdr set))))))
You will then discover another problem, which is that you meant to construct a list containing the values referred to by element and (car set), not to quote that list. What is the difference between quote and list? will help you understand what's doing on there.
try this:
(define (helper element set)
(map (lambda(x) (cons element x)) set))

Scheme function to take a list and an atom as parameters and returns index of the first location where atom occurs

I'm very new to Scheme and am working on a problem defined as follows:
Write a scheme function find-loc which takes two parameters, a list lst and an atom atm, and returns the index of the first location where atm occurs in the list.
The location index is 1-relative. If atm does not occur in the list, the function returns n + 1, where n is the length of the list.
what I've got so far is:
(define (find-loc list atm)
(if (not(list? list))
0
(cond
((null? list)
1)
((eq? (car list)atm)
1))
(else (+ (find-loc (cdr list atm) 1) )))
I feel that I'm close but am a bit stuck. My main questions are as follows:
how do I define what the atom is?
why am I getting the following error? "define: expected only one expression for the function body, but found 1 extra part"
An atom is defined by this predicate:
(define (atom? x)
(and (not (null? x))
(not (pair? x))))
The error you're receiving is because the syntax of the if expression is incorrect - it must have two parts after the condition (consequent and alternative), and you wrote three. A few comments:
It's better to use a cond when testing for multiple conditions
Don't name a variable as list, it clashes with a built-in procedure of the same name
Better use equal? for testing equality, it's more general
We should use our new and shiny atom? predicate, as per the requirements - even though the null? check is redundant at this point
This is what I mean:
(define (find-loc lst atm)
(cond ((not (list? lst)) 0)
((null? lst) 1)
((and (atom? (car lst)) (equal? (car lst) atm)) 1)
(else (+ 1 (find-loc (cdr lst) atm)))))

Search and add to a list in Scheme

I want to search for an element in a list, like this one (it's a list of lists)
(name1 (name2 (name3 name4) (name5 (name6))) (name7 (name8 name9)) (name10 (name11 name12)) (name13))
and when I find that element I want to add to it.
Like search for name10 and then add a new name to the name11 and name12 group.
Any help is much appreciated!
(define (adder name2badded indexname treenode)
(display treenode)
(newline)
(cond
((null? treenode)#f) ;"Tree is null"))
((pair? treenode)
(if (adder name2badded indexname (car treenode))
(display "Gotcha!")
(adder name2badded indexname (cdr treenode))
)
) ;END pair?
(else
(eq? indexname treenode)
);END else
);END Cond
)
This is what I have so far, it will find the spot where I want to add it but I can't get to adding to that spot.
You must reconstruct the new tree on your way back from the found point, after you've added your new value there. So you must stop one level above where you're stopping now: at (name old-value ...) instead of at name. This means you must test for equality with (car treenode), not treenode itself. This way you'll be able to construct a new association group as
(cons (car treenode) (cons val2add (cdr treenode)))
and you need to alter your recursion structure to use this new updated assoc group instead of the old one, to reconstruct the whole tree on your way back:
(define (add-into val2add name tree)
(if (pair? tree)
(if (eqv? name (car tree))
(cons name (cons val2add (cdr tree))) ; found!
(cons (add-into val2add name (car tree)) ; it's in CAR or in CDR,
(add-into val2add name (cdr tree)))) ; or maybe in both?
tree))
But if your tree were actually an assoc list and you were allowed to use surgical routines, you could just use
(define (add-into! val2add name als)
(cond ((assv name als) =>
(lambda (a)
(set-cdr! a (cons val2add (cdr a)))))))

Finding element in list in Scheme

i'm very beginner of Scheme and try to figure out how it is functioning; so i want to write a basic code:
first of all i have a definition set: zipcode (ZIPCODE CITY STATE)
(define zipcodes '(
(96774 ookala hawaii)
(90001 losangeles california)
(90263 malibu california)
(10044 newyork newyork)
))
i try to write a function that input is zipcode and return city and state name for example:
>(find '10044)
(list 'newyork 'newyork)
>(find '99999)
empty because there is not zipcode like that.
Thanks a lot...
I'm not allowed to us LET function
Use assoc
> (assoc 90001 zipcodes)
(90001 losangeles california)
> (cdr (assoc 90001 zipcodes))
(losangeles california)
(define filter
(lambda (proc lst)
(cond ((null? lst) '())
((proc (car lst)) (cons (car lst) (filter proc (cdr lst))))
(else
(filter proc (cdr lst))))))
(define find-zip
(lambda (zip lst)
(define match (filter (lambda (item) (= zip (car item))) lst))
(if (null? match)
'()
(cdar match))))
(define (find zip)
(find-zip zip zipcode))
I think that will work for you. Filter will apply its first argument (a procedure) to each item in its second argument, which needs to be a list. The first argument needs to return a boolean value for each item it's passed. Filter will then return a list with all of the items that returned true when the first argument was applied. Otherwise, it returns an empty list.
In this case, each item in the list you're passing is itself a list of 3 items, so it compares the first item in that list with the zip code you're looking for. If it's a match, it returns true. So if the zip code is in the list, it will return the three item sub-list. Then we check to see if we got an empty list, if so, then we return an empty list. Otherwise, we take the cdr of the car to get your desired city and state.
Well so you can basically just filter the list for the zip code, I have sketched some code below (I'd write it differently, except I don't know what you have available outside of what is defined in RnRS).
(define find-zip
(lambda (zip codelist)
(if (empty? codelist) empty
(if (= zip (car (car codelist)) (list (cadr (car codelist)) (caddr (car codelist)))
(find-zip zip (cdr codelist))))))
It would probably be better should you use a let, and I think most implementations have a filter function that let you do this better.

Scheme Compare item or list if it's inside the test list (can be nested)

My Goal is to make the function part? return true if a list or an item is inside the nested list.
But so far I can only get it working with signal item inside a first order list. (not nested list yet)
(define part?
(lambda (item l)
(and (not (null? l))
(or (= item (car l))
(part? item (cdr l))))))
my goal is to have
part? of (A (B)), (((B) A (B)) C) is #f and
part? of (A B), (C (A B) (C)) is #t
Where I should improve on this? How can I make the list to compare with the nested list?
DISCLAIMER: I haven't written scheme regularly in 20 years.
I think you want to think about this problem in terms of the whole lispy/schemey approach which is to establish your conditions.
Given an input, item, you want to find if a list contains that item.
A list may contain an item if the list is not null.
A list contains an item if the car of the list matches the item or if the car of the list contains the item
A list contains an item if the cdr of the list contains the item.
A final question to consider, what is the result of (part? '(a b) '(a b))?
I would write the code like this
(define part? (lambda (item l)
(cond ((null? l) f)
((or (same? item (car l)) (part? item (car l))))
(t (part? item (cdr l)))
)
))
(define same? (lambda (a b) (eq? a b)))
I used the cond structure because it fits well with problems of this sort - it just feels right to break the problem out - notice the null check. I wrote same? as a helper function in case you want to write it yourself. You could just as easily to it this way:
(define same? (lambda (a b)
(cond ((and (atom? a) (atom? b)) (eq? a b))
((and (list? a) (list? b)) (and (same? (car a) (car b)) (same? (cdr a) (cdr b))))
(f f)
)
))
which basically says that two items are the same if they are both atoms and they are eq or they are both lists and the cars are the same and the cdrs are the same, otherwise false.
You can just as easily rewrite same? as this:
(define same? (lambda (a b) (equal? a b)))
The point of doing that is that there is a bottleneck in the code - how to determine if two items are the same. If you break that bottleneck out into its own function, you can replace it with different mechanisms. I know you're not here yet, but you will be at one point: you will also be able to rewrite the code so that the predicate is passed in. Something like this (and more up-to-date scheme programmers, feel free to correct me):
(define part-pred? (lambda (same-pred item l)
(cond ((null? l) f)
((or (same-pred item (car l)) (part? item (car l))))
(t (part? item (cdr l)))
)
))
(define part-eq? (lambda (item l) (part-pred? 'eq? item l)))
(define part-same? (lambda (item l) (part-pred? 'same? item l)))
(define part-equal? (lambda (item l) (part-equal? 'equal? item l)))
This has now abstracted the notion of part to be a function that applies the part structural rules and an equality predicate which is supplied by you. That makes it really easy to change the rules. This will make more sense when you hit mapcar.
The problem with the = function used here is, that it is only defined for numbers. To test arbitrary data for equality, there are the predicates eq?, eqv?, and equal?. These are listed here from most discriminating (eq?, basically something like a pointer comparison) to least discriminating (equal? will consider type and structure). The eqv? predicate is somewhere in between (type-aware for numbers, otherwise like eq? for anything else).
To compare lists, you will usually use equal?.
Edit Details on these predicate can be found in the R6RS.
Your solution is missing the idea, since you're dealing with nested lists you need to check if each item in each list is a list itself, if it is then check if the given list is part of the other or part of the rest of the list if not then you need to check the first items are equal and if the rest of the given list is part of the other.
(define part? item l
(cond (and (list? (car item)) (not (list? (car l))) ...)
(and (not (list? (car item))) (list? (car l)) ...)
(and (not (list? (car item))) (not (list? (car l))) ...)
(and (list? (car item)) (list? (car l))) ...)