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

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))))

Related

using basic build-in or standard function(s) to solve problems in 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 *))

For loop which prints out every 3rd number

I'm trying to make a for loop that iterates over a list of numbers and prints out every 3rd number.
Edit: I've only figured out how to use the for loop but I'm not entirely sure if there's a specific function I can use to only show every 3rd number. I feel like I might be on the right path when using car/cdr function except I'm getting an error
rest: contract violation
expected: (and/c list? (not/c empty?))
given: 0
My code:
(for/list ([x (in-range 20)] #:when (car(cdr(cdr x)))) (displayln x))
I'm trying to make a for loop that iterates over a list of numbers and prints out every 3rd number.
Typically it is more useful to create a new list with the desired values, and then print those values, or pass them to a function, or do whatever else may be needed. for/list does indeed return a list, and this is one reason for problems encountered by OP example code. (Other problems in OP code include that x is a number with [x (in-range 20)], so (cdr x) is not defined).
A possible solution would be to recurse over the input list, using take to grab the next three values, keeping the third, and using drop to reduce the input list:
;; Recurse using `take` and `drop`:
(define (every-3rd-1 lst)
(if (< (length lst) 3)
'()
(cons (third (take lst 3))
(every-3rd-1 (drop lst 3)))))
Another option would be to recurse on the input list using an auxiliary counter; starting from 1, only keep the values from the input list when the counter is a multiple of 3:
;; Recurse using an auxilliary counter:
(define (every-3rd-2 lst)
(define (every-3rd-helper lst counter)
(cond [(null? lst)
'()]
[(zero? (remainder counter 3))
(cons (first lst) (every-3rd-helper (rest lst) (add1 counter)))]
[else (every-3rd-helper (rest lst) (add1 counter))]))
(every-3rd-helper lst 1))
Yet another possibility would be to use for/list to build a list; here i is bound to values from the input list, and counter is bound to values from a list of counting numbers:
;; Use `for/list` to build a list:
(define (every-3rd-3 lst)
(for/list ([i lst]
[counter (range 1 (add1 (length lst)))]
#:when (zero? (remainder counter 3)))
i))
This function (or any of them, for that matter) could be usefully generalized to keep every nth element:
;; Generalize to `every-nth`:
(define (every-nth n lst)
(for/list ([i lst]
[counter (range 1 (add1 (length lst)))]
#:when (zero? (remainder counter n)))
i))
Finally, map could be used to create a list containing every nth element by mapping over a range of every nth index into the list:
;; Use `map` and `range`:
(define (every-nth-map n lst)
(map (lambda (x) (list-ref lst x)) (range (sub1 n) (length lst) n)))
If what OP really requires is simply to print every third value, rather than to create a list of every third value, perhaps the code above can provide useful materials allowing OP to come to a satisfactory conclusion. But, each of these functions can be used to print results as OP desires, as well:
scratch.rkt> (for ([x (every-3rd-1 '(a b c d e f g h i j k l m n o p))])
(displayln x))
c
f
i
l
o
scratch.rkt> (for ([x (every-3rd-2 '(a b c d e f g h i j k l m n o p))])
(displayln x))
c
f
i
l
o
scratch.rkt> (for ([x (every-3rd-3 '(a b c d e f g h i j k l m n o p))])
(displayln x))
c
f
i
l
o
scratch.rkt> (for ([x (every-nth 3 '(a b c d e f g h i j k l m n o p))])
(displayln x))
c
f
i
l
o
scratch.rkt> (for ([x (every-nth-map 3 '(a b c d e f g h i j k l m n o p))])
(displayln x))
c
f
i
l
o
Here is a template:
(for ([x (in-list xs)]
[i (in-naturals]
#:when some-condition-involving-i)
(displayln x))

Can anyone help me with a recursive function in racket?

I am writing a recursive function. But the question requires you not to use the exponential function. Can anyone show me how to get larger powers by multiplying smaller powers by a?
Input a=2 n=4. Then get[2, 4, 8, 16]
Input a=3 n=4. Then get[3 9 27 81].
I was trying to multiply a by a each time, so when I input 2 and 4. I get [2 4 16 256]. So what should I do?
Here is what I have written:
(define (input a n)
(if (= n 0)
'()
(append (cdr (list [* a a] a))
(let ((a (* a a)))
(input a (- n 1))))))
You are approaching the problem wrong, you really need two recursive functions (one to build the list and one to build each element). I am assuming you are allowed to use local, but if you aren't you could move that into a helper function.
(define (build-sqr-list a n)
(local [(define (sqr-recurse a n)
(if (= n 0)
1
(* a (sqr-recurse a (sub1 n)))))]
(if (= n 0)
'()
(cons (sqr-recurse a n) (build-sqr-list a (sub1 n))))))

"application: not a procedure" while computing binomial

I am defining a function binomial(n k) (aka Pascal's triangle) but am getting an error:
application: not a procedure;
expected a procedure that can be applied to arguments
given: 1
arguments...:
2
I don't understand the error because I thought this defined my function:
(define (binomial n k)
(cond ((or (= n 0) (= n k)) 1)
(else (+ (binomial(n) (- k 1))(binomial(- n 1) (- k 1))))))
In Scheme (and Lisps in general), parentheses are placed before a procedure application and after the final argument to the procedure. You've done this correctly in, e.g.,
(= n 0)
(= n k)
(- k 1)
(binomial(- n 1) (- k 1))
However, you've got an error in one of your arguments to one of your calls to binomial:
(define (binomial n k)
(cond ((or (= n 0) (= n k)) 1)
(else (+ (binomial(n) (- k 1))(binomial(- n 1) (- k 1))))))
***
Based on the syntax described above (n) is an application where n should evaluate to a procedure, and that procedure will be called with no arguments. Of course, n here actually evaluates to an integer, which is not a procedure, and can't be called (hence “application: not a procedure”). You probably want to remove the parentheses around n:
(binomial n (- k 1))
It's also worth pointing out that Dr. Racket should have highlighted the same portion of code that I did above. When I load your code and evaluate (binomial 2 1), I get the following results in which (n) is highlighted:
Your error is here:
binomial(n)
n is an integer, not a function. If you put parentheses around it like that, scheme tries to invoke an integer as a function, which naturally produces an error.
This is the correct code:
(define (binomial n k)
(cond ((or (= n 0) (= n k)) 1)
(else (+ (binomial n (- k 1))(binomial(- n 1) (- k 1))))))
Problem is at here:
(binomial (n) (- k 1))

Scheme/Racket: do loop order of evaluation

The following procedure is valid in both scheme r6rs and Racket:
;; create a list of all the numbers from 1 to n
(define (make-nums n)
(do [(x n (- x 1)) (lst (list) (cons x lst))]
((= x 0)
lst)))
I've tested it for both r6rs and Racket and it does work properly, but I only know that for sure for DrRacket.
My question is if it is guaranteed that the step expressions ((- x 1) and (cons x lst) in this case) will be evaluated in order. If it's not guaranteed, then my procedure isn't very stable.
I didn't see anything specifying this in the standards for either language, but I'm asking here because when I tested it was evaulated in order.
They're generally not guaranteed to be evaluated in order, but the result will still be the same. This is because there are no side-effects here -- the loop doesn't change x or lst, it just rebinds them to new values, so the order in which the two step expressions are evaluated is irrelevant.
To see this, start with a cleaner-looking version of your code:
(define (make-nums n)
(do ([x n (- x 1)] [lst null (cons x lst)])
[(zero? x) lst]))
translate to a named-let:
(define (make-nums n)
(let loop ([x n] [lst null])
(if (zero? x)
lst
(loop (- x 1) (cons x lst)))))
and further translate that to a helper function (which is what a named-let really is):
(define (make-nums n)
(define (loop x lst)
(if (zero? x)
lst
(loop (- x 1) (cons x lst))))
(loop n null))
It should be clear now that the order of evaluating the two expressions in the recursive loop call doesn't make it do anything different.
Finally, note that in Racket evaluation is guaranteed to be left-to-right. This matters when there are side-effects -- Racket prefers a predictable behavior, whereas others object to it, claiming that this leads people to code that implicitly relies on this. A common small example that shows the difference is:
(list (read-line) (read-line))
which in Racket is guaranteed to return a list of the first line read, and then the second. Other implementations might return the two lines in a different order.