How do I calculate non-natural logarithms in Racket? - lisp

I am aware of racket's log function, which computers the natural logarithm of a number. I am trying to find the logarithms of numbers raised to arbitrary bases. In other words, instead of this:
> (log 9)
2.1972245773362196
I would like to do something similar to this:
> (logarithm 3 9)
2
Is there a function anyone knows about either builtin to Racket or available in a module from PLaneT I can use like this?

Use math: logk n = ln n / ln k:
(/ (log 9) (log 3))

Racket 6.9.0.1 added a second argument for arbitrary bases. logkn can now be written as (log n k).
According to the docs, this is equivalent to (/ (log n) (log k)), but possibly faster.
log entry in the documentation.

Related

Emacs: Turn off pretty printing in racket-mode

I am running Emacs 24.5.1 on Windows 10 and working through the SICP. The MIT editor Edwin doesn't function well, especially on Windows. Racket appears to be a good alternative. I have installed both Racket and racket-mode and everything seems to run okay. However, racket-mode insists on pretty-printing my results. How do I get it to print in decimal form?
For example,
(require sicp)
(define (square x) (* x x))
(define (average x y)
(/ (+ x y) 2))
(define (improve guess x)
(average guess (/ x guess)))
(define (good-enough? guess x)
(< (abs (- (square guess) x)) 0.001))
(define (sqrt-iter guess x)
(if (good-enough? guess x)
guess
(sqrt-iter (improve guess x)
x)))
This produces results such as
> (sqrt-iter 1 2)
577/408
Lots of documentation comes up when I Google the terms "Racket" and "pretty-print," but I'm having no luck making sense of it. The Racket documentation seems to control pretty-printing via some variable beginning with 'pretty-print'. Yet nothing starting with racket- or pretty within M-x comes up. Maybe the fraction form isn't what Racket considers pretty-printing?
Start the the iteration with floating point numbers 1.0 and 2.0 rather than exact numbers 1 and 2.
The literal 1 is read as an exact integer whereas 1.0 or 1. is read as a floating point number.
Now the function / works on both exact an inexact numbers. If fed exact numbers it produces a fraction (which eventually ends up being printed in the repl).
That is you are not seeing the effect of a pretty printer, but the actual result. The algorithm works efficiently only on floating point numbers as input so you can consider adding a call to exact->inexact to your function.
As the other answers explain, it turned out this isn't actually about pretty printing.
However to answer you question literally (if you ever did want to disable pretty printing in racket-mode):
The Emacs variable is racket-pretty-print.
You can view documentation about it using C-h v.
To change it you can either:
Use Emacs' M-x customize UI.
Use (setq racket-pretty-print nil) in your Emacs init file, for example in a racket-repl-mode-hook.
This is actually intentional and is part of the Scheme standard (R5RS, R7RS). It is not restricted to Racket but should be the output of any Scheme interpreter/REPL. It has nothing to do with pretty printing. It is mostly considered a good thing since it is giving you the exact number (rational number) rather than a floating point approximation. If you do want the floating point result then do request it by using 1.0 rather than 1 etc.
> (/ 1.0 3)
0.3333333333333333
Alternatively, you can use the exact->inexact function e.g.
> (exact->inexact 1/3)
0.3333333333333333

How to apply lambda calculus rules in Racket?

I am trying to test some of the lambda calculus functions that I wrote using Racket but not having much luck with the testcases. For example given a definition
; successor function
(define my_succ (λ (one)
(λ (two)
(λ (three)
(two ((one two) three))))))
I am trying to apply it to 1 2 3, expecting the successor of 2 to be 3 by doing
(((my_succ 1) 2) 3)
logic being that since my_succ is a function that takes one arg and passes it to another function that takes one arg which passes it to the third function that takes one arg. But I get
application: not a procedure;
expected a procedure that can be applied to arguments
given: 1
arguments.:
I tried Googling and found a lot of code for the rules, but no examples of application of these rules. How should I call the above successor function in order to test it?
You are mixing two completely different things: lambda terms and functions in Racket.
In Racket you can have anonymous functions, that can be written in the λ notation (like (λ(x) (+ x 1)) that returns the successor of an integer, so that ((λ(x) (+ x 1)) 1) returns 2),
in Pure Lambda Calculus you have only lambda terms, that are written with in a similar notation, and that can be interpreted as functions.
In the second domain, you do not have natural numbers like 0, 1, 2, ..., but you have only lambda terms, and represent numbers as such. For instance, if you use the so-called Church numerals, you represent (in technical term encode) the number 0 with the lambda term λf.λx.x, 1 with λf.λx.f x, 2 with λf.λx.f (f x) and so on.
So, the function successor (for numbers represented with this encoding) correspond to a term which, in Racket notation, is the function that you have written, but you cannot apply it to numbers like 0, 1, etc., but only to other lambda expressions, that is you could write something like this:
(define zero (λ(f) (λ (x) x))) ; this correspond to λf.λx.x
(successor zero)
The result in Racket is a procedure (it will be printed as: #<procedure>), but if you try to test that your result is correct, comparing it with the functional encoding of 1, you will find something strange. In fact:
(equal? (successor zero) (λ(f) (λ(x) (f x))))
produces #f, since if you compare two procedures in Racket you obtain always false (e.g. (equal? (λ(x)x) (λ(x)x)) produces #f), unless you compare the “identical” (in the sense of “same memory cell”) value ((equal? zero zero) gives #t). This is due to the fact that, for comparing correctly two functions, you should compare infinite sets of couples (input, output)!
Another possibility would be representing lambda terms as some kind of structure in Racket, so you can represent Church numerals, as well as "normal" lambda terms, and define a function apply (or better reduce) the perform lambda-reduction.
You are trying to apply currying.
(define my_succ
(lambda(x)(
lambda(y)(
lambda(z)(
(f x y z)))))
(define (add x y z)
(+ x y z))
((( (my_succ add)1)2)3)
Implementation in DR Racket:

How to define a function that returns half of input, in two different ways?

I am reading a Gentle Introduction to Symbolic Computation and it asks this question. Basically, the previous content deals with making up bigger functions with small ones. (Like 2- will be made of two 1- (decrement operators for lisp))
So one of the questions is what are the two different ways to define a function HALF which returns one half of its input. I have been able to come up with the obvious one (dividing number by 2) but then get stuck. I was thinking of subtracting HALF of the number from itself to get half but then the first half also has to be calculated...(I don't think the author intended to introduce recursion so soon in the book, so I am most probably wrong).
So my question is what is the other way? And are there only two ways?
EDIT : Example HALF(5) gives 2.5
P.S - the book deals with teaching LISP of which I know nothing about but apparently has a specific bent towards using smaller blocks to build bigger ones, so please try to answer using that approach.
P.P.S - I found this so far, but it is on a completely different topic - How to define that float is half of the number?
Pdf of book available here - http://www.cs.cmu.edu/~dst/LispBook/book.pdf (ctrl+f "two different ways")
It's seems to be you are describing peano arithmetic. In practice it works the same way as doing computation with fluids using cups and buckets.
You add by taking cups from the source(s) to a target bucket until the source(s) is empty. Multiplication and division is just advanced adding and substraction. To halve you take from source to two buckets in alterations until the source is empty. Of course this will either do ceil or floor depending on what bucket you choose to use as answer.
(defun halve (x)
;; make an auxillary procedure to do the job
(labels ((loop (x even acc)
(if (zerop x)
(if even (+ acc 0.5) acc)
(loop (- x 1) (not even) (if even (+ acc 1) acc)))))
;; use the auxillary procedure
(loop x nil 0)))
Originally i provided a Scheme version (since you just tagged lisp)
(define (halve x)
(let loop ((x x) (even #f) (acc 0))
(if (zero? x)
(if even (+ acc 0.5) acc)
(loop (- x 1) (not even) (if even (+ acc 1) acc)))))
Edit: Okay, lets see if I can describe this step by step. I'll break the function into multiple lines also.
(defun half (n)
;Takes integer n, returns half of n
(+
(ash n -1) ;Line A
(if (= (mod n 2) 1) .5 0))) ;Line B
So this whole function is an addition problem. It is simply adding two numbers, but to calculate the values of those two numbers requires additional function calls within the "+" function.
Line A: This performs a bit-shift on n. The -1 tells the function to shift n to the right one bit. To explain this we'll have to look at bit strings.
Suppose we have the number 8, represented in binary. Then we shift it one to the right.
1000| --> 100|0
The vertical bar is the end of the number. When we shift one to the right, the rightmost bit pops off and is not part of the number, leaving us with 100. This is the binary for 4.
We get the same value, however if we perform the shift on nine:
1001| --> 100|1
Once, again we get the value 4. We can see from this example that bit-shifting truncates the value and we need some way to account for the lost .5 on odd numbers, which is where Line B comes in.
Line B: First this line tests to see if n is even or odd. It does this by using the modulus operation, which returns the remainder of a division problem. In our case, the function call is (mod n 2), which returns the remainder of n divided by 2. If n is even, this will return 0, if it is odd, it will return 1.
Something that might be tripping you up is the lisp "=" function. It takes a conditional as its first parameter. The next parameter is the value the "=" function returns if the conditional is true, and the final parameter is what to return if the conditional is false.
So, in this case, we test to see if (mod n 2) is equal to one, which means we are testing to see if n is odd. If it is odd, we add .5 to our value from Line A, if it is not odd, we add nothing (0) to our value from Line A.

does emacs has rational number data type

I eval a lisp expression in scratch
(+ (/ 1 2) (/ 1 2))
I got a 0.
normally it should be 1.
As Oleg points out, operators usually default to integer arithmetic unless you include floating point arguments (like 1.0).
With respect to your question about rational number support, emacs-calc (which is part of emacs) supports many number types including fractions (i.e. rational numbers), complex numbers, infinite precision integers, etc. Your code must call emacs-calc functions (instead of /, etc.) in order to use calc's arithmetic.
GNU Emacs Calc Manual:
Fractions
Index of Lisp Math Functions
Try this way
(+ (/ 1.0 2) (/ 1.0 2))
According to emacs doc
Function: / dividend divisor &rest divisors
if all the arguments are integers, then the result is an integer too.
You can read all about numbers in elisp here:
C-hig (elisp) Numbers RET
As already indicated by tripleee, it is apparent that the answer is "no".
Emacs calc has rational data type: use colon, like 1:2 == 0.5 or 5:3 == 1 + 2:3 == 1:2:3.
This way Emacs calc simplifies expressions, for example if you deal with display resolutions for 1920:1080 it prints 16:9! If you want 1440p with the 16:9 ratio: 1440 * 16:9 ⇒ 2560.

Lisp: How to write a Higher Order Function

I have this problem to work on:
The sum higher order procedure can be generalised even further to capture the idea of combining terms with a fixed operator. The mathematical product operator is a specific example of this idea, with multiplication replacing the addition of the summation operator.
The procedure accumulate, started below, is intended to capture this idea. The combiner parameter represents the operator that is used to reduce the terms, and the base parameter represents the value that is returned when there are no terms left to be combined. For example, if we have already implemented the accumulate procedure, then we could define the sum procedure as:
(define sum (accumulate + 0))
Complete the definition of accumulate so that it behaves according to this description.
(define accumulate
(lambda (combiner base)
(lambda (term start next stop)
(if (> start stop)
...
...))))
I inserted as the last two lines:
base
(combiner base (accumulate (combiner start stop) start next stop))
but, I have no idea if this is correct nor how to actually use the sum procedure to call accumulate and hence sum up numbers.
This is a great way to learn how to fish. Much better
than being given a fish.
Until then, here's how to approach the problem. Write a
function which would do what (accumulate + 0) would do. Don't use the accumulate function; just write a defun which which does what your homework asks. Next, write a function which would do what (accumulate * 1) would do. What are the similarities, what are the differences between the two functions. For the most part, they should be identical except for the occurrence of the + and * operators.
Next, note that the accumulate function is to return a function which will look a lot like the two functions you wrote earlier. Now, using the insight that two functions you wrote are very similar, think how to apply that to the function which (defun accumulate ...) is to return.