Using Racket to Plot Points - plot

After spending some time looking at the documentation, searching the web, and experimenting at the prompt, I haven't succeeded at plotting points using Racket. Could someone post an example of how I'd go about plotting (0 1 2 3 4 5) for my x coordinates and (0 1 4 9 16 25) for the y coordinates. I think 1 good example will clear the problem up.

Based on the first example of the doc, and given that the function you want to plot already exists in Racket, it's as simple as:
(require plot)
(plot (function sqr 0 5 #:label "y = x ^ 2"))
If you just want to see the individual points, this is also taken from the docs:
(require plot)
(define xs '(0 1 2 3 4 5))
(define ys '(0 1 4 9 16 25))
(plot (points (map vector xs ys) #:color 'red))
which is equivalent to
(require plot)
(plot (points '(#(0 0) #(1 1) #(2 4) #(3 9) #(4 16) #(5 25)) #:color 'red))

Related

Recursive Multiplication in Scheme (positive numbers)

I am new to scheme and am trying to gain an understanding of how the following piece of code is able to recursively multiply two numbers provided (how is the function stack occurring here):
;Recursive Arithmetic
(define increment
(lambda (x)
(+ x 1)))
(define decrement
(lambda (x)
(- x 1)))
(define recursive-add
(lambda (x y)
(if (zero? y)
x
(recursive-add (increment x) (decrement y)))))
"Define Multiplication Recursively"
(define recursive-mult
(lambda (x y)
(if (zero? y)
0
(recursive-add x (recursive-mult x (decrement y)))))) ;else
(recursive-mult 9 5)
My first doubt is what part of the else section is executed first?
In the else section, if (decrement y) is executed first, then y is first decremented by 1, then the(recursive-mult x section runs next by which function calls itself, so the section (recursive-add x never gets called in this same line of code.
Now, if in the else section, the recursive-add x is executed first, x gets added first, then the recursive-mult x runs which runs the the whole function again and the (decrement y) is never reached.
Now I know either of my two assumptions above, or maybe both are wrong. Would someone be able to point me in the right direction please? I apologize if my question displays a high level of inadequacy in this subject but I really want to learn scheme properly. Thank you.
This is an answer in Common Lisp, in which I am more familiar, but the approach is the same. Here is a translation of your code:
(defpackage :so (:use :cl))
(in-package :so)
(defun add (x y)
(if (zerop y)
x
(add (1+ x) (1- y))))
(defun mul (x y)
(if (zerop y)
0
(add x (mul x (1- y)))))
The increment and decrement functions are not defined, I'm using 1+ and 1- which are equivalent.
In the else section, if (decrement y) is executed first, then y is first decremented by 1, then the(recursive-mult x section runs next by which function calls itself, so the section (recursive-add x never gets called in this same line of code.
You can use the substitution model to evaluate recursive functions.
(add (add 1 3) 1)
Let's evaluate first the first argument of the top-most and:
(add (add 2 2) 1)
(add (add 3 1) 1)
(add (add 4 0) 1)
(add 4 1)
Here the call eventually returned and the first argument is 4. Once the execution is resumed, the rest of the code for (add (add 1 3) 1) is executed, which is equivalent to:
(add 5 0)
And finally:
5
Each time you invoke the function a new frame is pushed on the call stack, which is what is shown in a trace:
(trace mul add)
The macro above in Common Lisp makes it so the mul and add functions are traced.
Now when I run a program, a trace is printed when they are entered and exited.
Let's try with small values:
(mul 2 3)
The trace is printed as follows (don't mind the SO:: prefix, this is part of the fully-qualified name of symbols):
0: (SO::MUL 2 3)
1: (SO::MUL 2 2)
2: (SO::MUL 2 1)
3: (SO::MUL 2 0)
3: MUL returned 0
3: (SO::ADD 2 0)
3: ADD returned 2
2: MUL returned 2
2: (SO::ADD 2 2)
3: (SO::ADD 3 1)
4: (SO::ADD 4 0)
4: ADD returned 4
3: ADD returned 4
2: ADD returned 4
1: MUL returned 4
1: (SO::ADD 2 4)
2: (SO::ADD 3 3)
3: (SO::ADD 4 2)
4: (SO::ADD 5 1)
5: (SO::ADD 6 0)
5: ADD returned 6
4: ADD returned 6
3: ADD returned 6
2: ADD returned 6
1: ADD returned 6
0: MUL returned 6
The difference with Scheme is that Scheme does not define the order by which function arguments are evaluated (it is left unspecified), so maybe your code would not exactly behave as above, but it should still compute the same answer (because there are no side effects).
Scheme has eager evaluation so if you have
(op1 expr1 (op2 1 (op3 expr2 expr3)))
Then op1 form will depend on expr1 and the form with op2 to be complete before op1 can be applied. If we have an implementation that
does left to right evaluation it will do it like this:
(let ((vexpr1 expr1)
(vexpr2 expr2)
(vexpr3 expr3))
(let ((vop3 (op3 vexpr2 vexpr3)))
(let ((vop2 (op2 1 vop3)))
(op1 vexpr1 vop2))))
So to answer your question the order in the same left to right Scheme will be:
(let ((vdy (decrement y)))
(let ((vrm (recursive-mult x vdy)))
(recursive-add x vrm)))
Same in CPS:
(decrement& y
(lambda (vdy)
(recursive-mult& x
vy
(lambda (vrm)
(recursive-add& x vrm continuation)))))
So in practice the application for the first round doesn't happen before the whole recursive-mult for the smaller expression happens first. Thus (recursive-mult 3 3) turns into
(recursive-add 3 (recursive-add 3 (recursive-add 3 0)))
And as you can see the last one is being done first, then the second one and the last addition to be performed is the one of the first round before recursion.

How does scramble function works? (Chapter 1 of The Seasoned Schemer)

According to the book, this is what the function definition is,
The function scramble takes a non-empty tuple in which no argument is greater than its own index and returns a tuple of same length. Each number in the argument is treated as a backward index from its own position to a point earlier in tuple. The result at each position is obtained by counting backward from the current position according to this index.
And these are some examples,
; Examples of scramble
(scramble '(1 1 1 3 4 2 1 1 9 2)) ; '(1 1 1 1 1 4 1 1 1 9)
(scramble '(1 2 3 4 5 6 7 8 9)) ; '(1 1 1 1 1 1 1 1 1)
(scramble '(1 2 3 1 2 3 4 1 8 2 10)) ; '(1 1 1 1 1 1 1 1 2 8 2)
Here is the implementation,
(define pick
(λ (i lat)
(cond
((eq? i 1) (car lat))
(else (pick (sub1 i)
(cdr lat))))))
(define scramble-b
(lambda (tup rev-pre)
(cond
((null? tup) '())
(else
(cons (pick (car tup) (cons (car tup) rev-pre))
(scramble-b (cdr tup)
(cons (car tup) rev-pre)))))))
(define scramble
(lambda (tup)
(scramble-b tup '())))
This is a case where using a very minimal version of the language means that the code is verbose enough that understanding the algorithm is not perhaps easy.
One way of dealing with this problem is to write the program in a much richer language, and then work out how the algorithm, which is now obvious, is implemented in the minimal version. Let's pick Racket as the rich language.
Racket has a function (as does Scheme) called list-ref: (list-ref l i) returns the ith element of l, zero-based.
It also has a nice notion of 'sequences' which are pretty much 'things you can iterate over' and a bunch of constructs whose names begin with for for iterating over sequences. There are two functions which make sequences we care about:
in-naturals makes an infinite sequence of the natural numbers, which by default starts from 0, but (in-naturals n) starts from n.
in-list makes a sequence from a list (a list is already a sequence in fact, but in-list makes things clearer and there are rumours also faster).
And the iteration construct we care about is for/list which iterates over some sequences and collects the result from its body into a list.
Given these, then the algorithm is almost trivial: we want to iterate along the list, keeping track of the current index and then do the appropriate subtraction to pick a value further back along the list. The only non-trivial bit is dealing with zero- vs one-based indexing.
(define (scramble l)
(for/list ([index (in-naturals)]
[element (in-list l)])
(list-ref l (+ (- index element) 1))))
And in fact if we cause in-naturals to count from 1 we can avoid the awkward adding-1:
(define (scramble l)
(for/list ([index (in-naturals 1)]
(element (in-list l)))
(list-ref l (- index element))))
Now looking at this code, even if you don't know Racket, the algorithm is very clear, and you can check it gives the answers in the book:
> (scramble '(1 1 1 3 4 2 1 1 9 2))
'(1 1 1 1 1 4 1 1 1 9)
Now it remains to work out how the code in the book implements the same algorithm. That's fiddly, but once you know what the algorithm is it should be straightforward.
If the verbal description looks vague and hard to follow, we can try following the code itself, turning it into a more visual pseudocode as we go:
pick i [x, ...ys] =
case i {
1 --> x ;
pick (i-1) ys }
==>
pick i xs = nth1 i xs
(* 1 <= i <= |xs| *)
scramble xs =
scramble2 xs []
scramble2 xs revPre =
case xs {
[] --> [] ;
[x, ...ys] -->
[ pick x [x, ...revPre],
...scramble2 ys
[x, ...revPre]] }
Thus,
scramble [x,y,z,w, ...]
=
[ nth1 x [x] (*x=1..1*)
, nth1 y [y,x] (*y=1..2*)
, nth1 z [z,y,x] (*z=1..3*)
, nth1 w [w,z,y,x] (*w=1..4*)
, ... ]
Thus each element in the input list is used as an index into the reversed prefix of that list, up to and including that element. In other words, an index into the prefix while counting backwards, i.e. from the element to the left, i.e. towards the list's start.
So we have now visualized what the code is doing, and have also discovered requirements for its input list's elements.

Racket can't plot a surface

I want to plot this surface:
z = (3x - 8 + 11y) / (6y -11)
Here is the code
(plot3d (surface
(lambda (x y) (/ (+ (* 3 x) -8 (* 11 y)) (- (* 6 y) 11)) 0 1 0 1))
#:x-min 0 #:x-max 1 #:y-min 0 #:y-max 1)
However, Racket produces a strange (and wrong graph). I try this function on academo.org and it plots just fine.
https://academo.org/demos/3d-surface-plotter/?expression=(3x-8%2B11y)%2F(6y-11)&xRange=0%2C1&yRange=0%2C1&resolution=25
Does anybody knows why? Because I need to plot multiple surfaces in a same graph and I cannot do that on academo. I have only Racket as graphing tool on my laptop.
Thank you,
Use surface3d (not surface). Easy oversight.
Sorry, surface does not work but surface3d works.
(plot3d (surface3d
(lambda (x y) (/ (+ (* 3 x) -8 (* 11 y)) (- (* 6 y) 11))) 0 1 0 1))
Though I still do not know why.

Creating a function to pair the corresponding elements in 2 lists

I am learning to use scheme and practicing by creating functions from practice problems I saw in a book. This one is called zipper.
I have already made the zipper function using recursion with only cons, car, and cdr.
Now I am trying to make this same function again but also using map or fold.
The function takes in two lists and 'zips' them together:
(zip '(1 2 3) '(4 5 6))
==> '((1 4) (2 5) (3 6))
How can I do this using either map or fold?
It may become clearer if the function to be used by map is declared separately:
(define (zip1 x y)
(list x y))
(map zip1 '(1 2 3) '(4 5 6)) ; corresponding elements of 2 lists will be sent to zip1
Since zip1 is only 'list', following also works:
(map list '(1 2 3) '(4 5 6))
Output for both:
'((1 4) (2 5) (3 6))
Hence to do (zip L1 L2), one does not need to write special zip function, one can just do (map list L1 L2).
This can also be used for any number of lists, e.g. (map list L1 L2 L3 L4) which may be an advantage over custom-made zip function made for 2 lists only.
The Racket documentation for map provides the following example:
> (map (lambda (number1 number2)
(+ number1 number2))
'(1 2 3 4)
'(10 100 1000 10000))
'(11 102 1003 10004)
Notice that this is very similar to what you are trying to achieve, but instead of mapping the + function between corresponding elements in two lists, you can map a list function, as follows:
> (map (lambda (number1 number2)
(list number1 number2))
'(1 2 3 4)
'(10 100 1000 10000))
'((1 10) (2 100) (3 1000) (4 10000))
and hence, a zip function becomes:
(define (zip lst1 lst2)
(map
(lambda(elem1 elem2)
(list elem1 elem2))
lst1 lst2))

Is (lambda (x) ... ) with parenthesis placed in a certain way used for limiting scope?

A classic enumeration using unfold:
(unfold-left (lambda (x)
(if (> x 10)
(#;no values)
(+ x 1)))
#;from 0)
===> (0 1 2 3 4 5 6 7 8 9 10))
if limiting the scope is not needed is there any way to just write x without the lambda?
unfold is implemented like this:
(define (unfold p f g seed (tail-gen (λ (_) '())))
(let recur ((seed seed))
(if (p seed)
(tail-gen seed)
(cons (f seed)
(recur (g seed))))))
As you can see p, f, g, and tail-gen are all procedures since they get surrounded by parentheses in the implementation. If they are not procedures you will get an application: not a procedure error.
You are using unfold wrong. you need a procedure that takes the current value and return wether or not you are finished. Second is a procedure that takes the seed and return what value to collect and the third is a procedure to create the next seed. The optional tail-gen takes the seed and creates the tail where the empty list will be used if not provided. Here is how you make a list from 0 to 10:
#lang racket
(require srfi/1)
(require srfi/26)
(unfold (cut > <> 10) identity add1 0)
; ==> (0 1 2 3 4 5 6 7 8 9 10)
And of course, (range 11) gives the same answer.

Resources