using basic build-in or standard function(s) to solve problems in racket? - racket

I'm working with lists in Racket, and I was doing a function to sum the elements of a list.
for example
(define (mysum L)
(if (empty? L) 0
(+ (first L) (mysum (rest L))))
)
then the result will be
> (mysum'(5 4))
9
>
But I would like to know what to do to multiply the numbers inside the list, rather than add them. when I put the * sign instead of + then it gives me an output of zero.
(define (myproduct L)
(if (empty? L) 0
(* (first L) (myproduct (rest L))))
)
and the result is
> (myproduct'(3 5))
0
> enter code here
I'm trying to understand how to multiply numbers in a list.

The myproduct should use 1 instead of 0 in the base case, because the identity element of multiplication is 1.
(define (myproduct L)
(if (empty? L) 1
(* (first L) (myproduct (rest L)))))
> (myproduct'(3 5))
15

A nice way to think about this is that * and + are the two operations of the field of numbers. And in any field, the two operations have identities, which are objects such that (<op> x <identity-of-op>) is x. But they have different identities. So let's define a function which tells us what the identity of the two operations is:
(define (identity-of op)
(cond
[(eqv? op +)
0]
[(eqv? op *)
1]
[else
(error "there are only two operations for the field of numbers")]))
And now we can define a general function which, given an operator, will return a function which combines a bunch of numbers using it (this function will be correct, since both * and + are associative):
(define (make-combiner op)
(define id (identity-of op))
(define (combiner numbers)
(if (null? numbers)
id
(op (first numbers) (combiner (rest numbers)))))
combiner)
And now:
(define sum-numbers (make-combiner +))
(define multiply-numbers (make-combiner *))

Related

How can I use more than "return" statement in the following piece of code?

In my else condition I have two statements to execute. The first one ought to append my calculation to my return-list and the second one calls my recursive procedure again.
The problem is that my append procedure is being ignored so I am just returning an empty list.
(define (calcit x lst)
(cond ((= x 0)
retlst)
(else (append (list (floor (/ x (first lst)))) retlst)
(calcit (modulo x (first lst)) (rest lst)))))
You need to do something with the data you are creating. You probably want to have the first element consed on the result of the list you get from the recursion:
(define (calcit x lst)
(if (= x 0)
'() ;; base case
(cons (floor (/ x (first lst)))
(calcit (modulo x (first lst)) (rest lst)))))
When creating lists in Scheme with recursion try to avoid append. Using append is an anti pattern. Learn how Scheme lists work and train to know it intimately. eg '((2 3) (4 5)) if I ask you how to get 5 from that you should think d a d a and answer cadadr almost right away.

Trying to get this code to work, can't understand where to put the argument in and keep getting errors

Define the function iota1(n, m) that takes positive integers n, m with n < m as input, and outputs the list (n,n+1,n+2,...,m)
I've tried switching the code around multiple times but cannot seem to get it to function and display a list the right way
(define (iota1 n m)
(if (eq? n 0)
'()
(append (iota1 (< n m) (+ n 1)) (list n))))
There's a few oddities to the code you provided, which I've formatted for readability:
(define (iota1 n m)
(if (eq? n 0)
'()
(append (iota (< n m) (+ n 1))
(list n))))
The first is that the expression (< n m) evaluates to a boolean value, depending on whether n is less than m or not. When you apply iota to (< n m) in the expression (iota (< n m) (+ n 1)), you are giving iota a boolean value for its first argument instead of a positive integer.
Secondly, the use of append is strange here. When constructing a list in Racket, it's much more common to use the function cons, which takes as arguments a value, and a list, and returns a new list with the value added to the front. For example,
(append '(3) (append '(4) (append '(5) '()))) ==> '(3 4 5)
(cons 3 (cons 4 (cons 5 '()))) ==> '(3 4 5)
It's a good idea to opt for using cons instead of append because it's simpler, and because it is faster, since cons does not traverse the entire list like append does.
Since this sounds a bit like a homework problem, I'll leave you with a "code template" to help you find the answer:
; n : integer
; m : integer
; return value : list of integers
(define (iota1 n m)
(if (> n m) ; base case; no need to do work when n is greater than m
... ; value that goes at the end of the list
(cons ... ; the value we want to add to the front of the list
(iota1 ... ...)))) ; the call to iota, generating the rest of the list
Welcome to the racket world, my version is here:
#lang racket
(define (iota1 n m)
(let loop ([loop_n n]
[result_list '()])
(if (<= loop_n m)
(loop
(add1 loop_n)
(cons loop_n result_list))
(reverse result_list))))

Racket: Product of even number

I am trying to produce the product of the even numbers in a given list.
I am trying to replicate the following example:
Example:
(product-even-numbers '(2 1 6 3 5))
==> 12
This is my version of the definition for product-even-numbers:
(define (product-even-numbers lst)
(define/match (recurse lst accumulator)
;; A _ pattern matches any syntax object
[(_ _) (* car (recurse cdr))])
(recurse lst 1))
I am getting the following error:
(product-even-numbers '(2 1 6 3 5))
. . recurse: arity mismatch;
the expected number of arguments does not match the given number
expected: 2
given: 1
arguments...:
I understand that i am missing the second argument, but I do not know what the second argument is supposed to be.
Why are you using pattern matching? this would be easier to understand without it, and first of all you need to get the recursion and the logic right:
(define (product-even-numbers lst)
(define (recurse lst acc)
(cond ((null? lst) acc)
((even? (car lst)) (recurse (cdr lst) (* (car lst) acc)))
(else (recurse (cdr lst) acc))))
(recurse lst 1))
In this case, it's clear that the second argument is the accumulated product we have so far. And we need to consider three cases: empty list, even element, odd element. For example:
(product-even-numbers '(2 1 6 3 5))
=> 12
(define (product-even-numbers lst)
(local [(define tmp (foldr * 1 (filter even? lst)))]
(if (= 1 tmp) 'nothing tmp)))
If output 1 means no any even number.
(define (product-even-numbers2 lst)
(foldr * 1 (filter even? lst))) ; or use (apply * (filter even? lst))

How to use foldr in Racket to eliminate numbers in a list that are greater than any subsequent numbers

I have to write a function in Racket using foldr that will take a list of numbers and remove list elements that are larger than any subsequent numbers.
Example: (eliminate-larger (list 1 2 3 5 4)) should produce (1 2 3 4)
I can do it without using foldr or any higher-order functions but I can't figure it out with foldr. Here's what I have:
(define (eliminate-larger lst)
(filter (lambda (z) (not(equal? z null)))
(foldr (lambda (x y)
(cons (determine-larger x (rest lst)) y)) null lst))
)
(define (determine-larger value lst)
(if (equal? (filter (lambda (x) (>= x value)) lst) lst)
value
null)
)
determine-larger will take in a value and a list and return that value if it is greater than or equal to all elements in the list. If not, it returns null. Now the eliminate-larger function is trying to go through the list and pass each value to determine-larger along with a list of every number after it. If it is a "good" value it will be returned and put in the list, if it's not a null is put in the list. Then at the end the nulls are being filtered out. My problem is getting the list of numbers that follow after the current number in the foldr function. Using "rest lst" doesn't work since it's not being done recursively like that. How do I get the rest of the numbers after x in foldr?
I really hope I'm not doing your homework for you, but here goes ...
How do I get the rest of the numbers after x in foldr?
Because you're consuming the list from the right, you can structure your accumulator such that "the rest of the numbers after x" are available as its memo argument.
(define (eliminate-larger lst)
(foldr
(lambda (member memo)
(if (andmap (lambda (n) (<= member n)) memo)
(cons member memo)
memo))
'()
lst))
(eliminate-larger (list 1 2 3 5 4)) ;; (1 2 3 4)
This is admittedly a naive solution, as you're forced to traverse the entire accumulator with each iteration, but you could easily maintain a max value, in addition to your memo, and compare against that each time through.
Following works:
(define (el lst)
(define (inner x lsti)
(if(empty? lsti) (list x)
(if(<= x (apply max lsti))
(cons x lsti)
lsti)))
(foldr inner '() lst))
(el (list 1 2 3 5 4))
Output:
'(1 2 3 4)
The cond version may be preferable:
(define (el lst)
(define (inner x lsti)
(cond
[(empty? lsti) (list x)]
[(<= x (apply max lsti)) (cons x lsti)]
[else lsti] ))
(foldr inner '() lst) )

How do I find the index of an element in a list in Racket?

This is trivial implement of course, but I feel there is certainly something built in to Racket that does this. Am I correct in that intuition, and if so, what is the function?
Strangely, there isn't a built-in procedure in Racket for finding the 0-based index of an element in a list (the opposite procedure does exist, it's called list-ref). However, it's not hard to implement efficiently:
(define (index-of lst ele)
(let loop ((lst lst)
(idx 0))
(cond ((empty? lst) #f)
((equal? (first lst) ele) idx)
(else (loop (rest lst) (add1 idx))))))
But there is a similar procedure in srfi/1, it's called list-index and you can get the desired effect by passing the right parameters:
(require srfi/1)
(list-index (curry equal? 3) '(1 2 3 4 5))
=> 2
(list-index (curry equal? 6) '(1 2 3 4 5))
=> #f
UPDATE
As of Racket 6.7, index-of is now part of the standard library. Enjoy!
Here's a very simple implementation:
(define (index-of l x)
(for/or ([y l] [i (in-naturals)] #:when (equal? x y)) i))
And yes, something like this should be added to the standard library, but it's just a little tricky to do so nobody got there yet.
Note, however, that it's a feature that is very rarely useful -- since lists are usually taken as a sequence that is deconstructed using only the first/rest idiom rather than directly accessing elements. More than that, if you have a use for it and you're a newbie, then my first guess will be that you're misusing lists. Given that, the addition of such a function is likely to trip such newbies by making it more accessible. (But it will still be added, eventually.)
One can also use a built-in function 'member' which gives a sublist starting with the required item or #f if item does not exist in the list. Following compares the lengths of original list and the sublist returned by member:
(define (indexof n l)
(define sl (member n l))
(if sl
(- (length l)
(length sl))
#f))
For many situations, one may want indexes of all occurrences of item in the list. One can get a list of all indexes as follows:
(define (indexes_of1 x l)
(let loop ((l l)
(ol '())
(idx 0))
(cond
[(empty? l) (reverse ol)]
[(equal? (first l) x)
(loop (rest l)
(cons idx ol)
(add1 idx))]
[else
(loop (rest l)
ol
(add1 idx))])))
For/list can also be used for this:
(define (indexes_of2 x l)
(for/list ((i l)
(n (in-naturals))
#:when (equal? i x))
n))
Testing:
(indexes_of1 'a '(a b c a d e a f g))
(indexes_of2 'a '(a b c a d e a f g))
Output:
'(0 3 6)
'(0 3 6)