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

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.

Related

Attempting to define a function that provides the minimum integer in a list of numbers SPECIFICALLY using do loops (not do* or dolist, etc.)

I have an assignment for class specifically testing our understanding of do, asking to define a function to produce the minimum of a list of numbers. We are asked to also use a secondary function ("smaller") to do so.
I have no previous experience coding, and am forced to stay within the boundaries of do; I've been reading up on the issue as much as I can, but almost everything I find just suggests using other methods (do*, COND, etc.).
I defined a simple "smaller" as:
(defun smaller (x y)
(if (< x y) x y))
I then approached the problem as such:
(defun minimum (lst)
"(lst)
Returns the minimum of a list of numbers."
(do ((numbers lst (cdr numbers))
(min (car numbers) (smaller min (cadr numbers))))
((null numbers) min)))
I feel there's an issue where the "smaller" function can't be applied on the first loop (feedback about this would be great), otherwise my immediate issue is getting an error of: "UNBOUND-VARIABLE" for the variable "NUMBERS". I am not sure which 'area' is causing the confusion: if I have poorly formatted the do loop entirely, or if one of the second/third/etc. "numbers" is causing an issue.
Can someone provide some feedback? -- again keeping in mind that we are limited specifically to simple do loops, and that I definitely don't have a perfect understanding of what I've already got down.
Thanks so much in advance.
Do binds in parallel, so numbers is not bound when min is first bound. You could fix that by using (car lst) instead of (car numbers) there.
You need to fix the end condition then: (cadr numbers) is nil on the last iteration, you need to stop before that.
For better readability, I'd suggest to use first and second instead of car and cadr here.
You could still refer to numbers as long as you used do*, which is a sequentially binding variant of do. Then you'd have to use car instead of cadr - you're now picking the first number from an already reduced list. And you'd need to modify your end condition to avoid calling smaller with a NIL argument - you should be able to figure this out easily.

Inaccuracy in number->string in Scheme

I am working on a Scheme program, where I need at some place a pair of a floatingpoint counter and the same counter as formated string. I am having issues with the number to string conversion.
Can someone explain me these inaccuracies in this code ?
(letrec ((ground-loop (lambda (times count step)
(if (= times 250)
(begin
(display "exit")
(newline)
)
(begin
(display (* times step)) (newline)
(display (number->string (* times step)))(newline)
(newline)
(newline)
(ground-loop (+ times 1) (* times step) step)
)
)
)
))
(ground-loop 0 0 0.05)
)
Part of the output looks like that
7.25
7.25
7.3
7.300000000000001
7.35
7.350000000000001
7.4
7.4
7.45
7.45
7.5
7.5
7.55
7.550000000000001
7.6
7.600000000000001
7.65
7.65
I am aware of floating point inaccuracies and tried several forms of increasing the counter but the issue is in the conversion itself.
Any ideas for an easy fix? Tried a bit with explicitly rounded numbers but this did not do the job. The results even vary from IDE and environment to environment. Do I really have to do string manipulation after conversion?
The very weird thing in my case is having an exact numeric result but the string is off.
Thank you
It looks to me as if:
the native float type (the type you get by reading 1.0) of your implementation is IEEE double float;
the display of your Scheme is not printing such floats 'correctly' (see below, I'm no sure this means it's buggy);
your number->string is doing the right thing.
By 'correctly' above I mean 'in a way so that reading what display printed returns an equivalent number'. I am not at all sure that display is required to be correct in this restrictive sense however, so I am not sure whether it's a bug. Someone who understands the Scheme standards better than I do might be able to comment on that.
In particular if the native float type of the languageis an IEEE double float, then, for instance:
(= (* 0.05 3) 0.15)
is false, as is
(= (* 0.05 146) 7.3)
Which is the example you have in the first line of your output.
So you certainly should not assume that your program will ever produce a number equal to the number you get by reading 7.3 for instance, because it won't.
In the above I have carefully avoided printing the numbers out, and that's because I'm not sure display is reliable on this, and in particular I'm not sure your display is reliable or that it is required to be.
Well, I have a Lisp implementation to hand which is reliable about this. In this system the default float format is a single-precision IEEE float, and I can get the reader to read double floats with, for instance 1.0d0. So, in this implementation you can see the results:
> (* 0.05d0 3)
0.15000000000000002D0
> (* 0.05d0 146)
7.300000000000001D0
And you'll see that these are exactly (up to the double-precision indicator) what number->string is giving you and not what display is giving you.
If what you want to do is to get a representation of the number in such a way that reading it will return an equivalent number, then number->string is what you should trust. In particular R5RS says in section 6.2.6 that:
(let ((number number)
(radix radix))
(eqv? number
(string->number (number->string number
radix)
radix)))
is true, and 'it is an error if no possible result makes this expression true'.
You can check the behaviour of number->float & float->number over a range of numbers by, for instance (this may assume a more recent or featurefull Scheme than you have):
(define (verify-float-conversion base times)
(define (good? f)
(eqv? (string->number (number->string f)) f))
(let loop ([i 0]
[bads '()])
(let ([c (* base i)])
(if (>= i times)
(values (null? bads) (reverse bads))
(loop (+ i 1) (if (good? c) bads (cons c bads)))))))
Then you should get
> (verify-float-conversion 0.05 10000)
#t
()
More generally using floats, still more floats that are the result of some computation more complicated than reading them some input source, as unique indices into any kind of tabular structure is fraught with danger to put it rather mildly: floating-point errors mean that it's just really dangerous to assume that (= a b) is true for floats even when it mathematically should be.
If you want such indices do exact arithmetic instead, and convert the results of that arithmetic to floats at the point you need to do computations. I believe (but am not sure) that Scheme implementations are nowadays required to support exact rational arithmetic (certainly this seems to be true for R6RS), so if you want to count 20ths (say) you can do so by counting in units of 1/20, which is exact, and then constructing floats when you need them.
It's probably safe to compare floats in the case that if you are for instance comparing a float you got by taking some initial float value and multiplying it by a machine integer and comparing it with some earlier version of itself which you have read by string->number. But if the calculation your doing is more complicated than that you need to be quite careful.

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:

extract/slice/reorder lists in (emacs) lisp?

In python, you might do something like
i = (0, 3, 2)
x = [x+1 for x in range(0,5)]
operator.itemgetter(*i)(x)
to get (1, 4, 3).
In (emacs) lisp, I wrote this function called extract which does something similar,
(defun extract (elems seq)
(mapcar (lambda (x) (nth x seq)) elems))
(extract '(0 3 2) (number-sequence 1 5))
but I feel like there should be something built in? All I know is first, last, rest, nth, car, cdr... What's the way to go? ~ Thanks in advance ~
If your problem is the speed then use (vector 1 2 3 4 5) instead of a list, and (aref vec index) to get the element.
(defun extract (elems seq)
(let ((av (vconcat seq)))
(mapcar (lambda (x) (aref av x)) elems)))
If you're going to extract from the same sequence many times of course it make sense to store the sequence in a vector just once.
Python lists are indeed one-dimensional arrays, the equivalent in LISP are vectors.
I've only done simple scripting in elisp, but it's a relatively small language. And extract is a very inefficient function on linked lists, which is the default data structure in emacs lisp. So it's unlikely to be built-in.
Your solution is the best straightforward one. It's n^2, but to make it faster requires a lot more code.
Below is a guess at how it might work, but it might also be totally off base:
sort elems (n log n)
create a map that maps elements in sorted elem to their indices in original elem (probably n log n, maybe n)
iterate through seq and sorted elem. Keep only the indices in sorted elem (probably n, maybe n log n, depending on whether it's a hash map or a tree map)
sort the result by the values of the elem mapping (n log n)
From My Lisp Experiences and the Development of GNU Emacs:
There were people in those days, in 1985, who had one-megabyte machines without virtual memory. They wanted to be able to use GNU Emacs. This meant I had to keep the program as small as possible.
For instance, at the time the only looping construct was ‘while’, which was extremely simple. There was no way to break out of the ‘while’ statement, you just had to do a catch and a throw, or test a variable that ran the loop. That shows how far I was pushing to keep things small. We didn't have ‘caar’ and ‘cadr’ and so on; “squeeze out everything possible” was the spirit of GNU Emacs, the spirit of Emacs Lisp, from the beginning.
Obviously, machines are bigger now, and we don't do it that way anymore. We put in ‘caar’ and ‘cadr’ and so on, and we might put in another looping construct one of these days.
So my guess is, if you don't see it, it's not there.

Odd question relating to project euler 72 (lisp)

I recognize that there's an obvious pattern in the output to this, I just want to know why lispbox's REPL aborts when I try to run anything > 52. Also, any suggestions on improving the code are more than welcome. ^-^
(defun count-reduced-fractions (n d sum)
(setf g (gcd n d))
(if (equal 1 d)
(return-from count-reduced-fractions sum)
(if (zerop n)
(if (= 1 g)
(count-reduced-fractions (1- d) (1- d) (1+ sum))
(count-reduced-fractions (1- d) (1- d) sum))
(if (= 1 g)
(count-reduced-fractions (1- n) d (1+ sum))
(count-reduced-fractions (1- n) d sum)))))
All I get when I call
(count-reduced-fractions 53 53 0)
is
;Evaluation aborted
It doesn't make much sense to me, considering it'll run (and return the accurate result) on all numbers below that, and that I could (if i wanted to) do 53 in my head, on paper, or one line at a time in lisp. I even tested on many different numbers greater than 53 to make sure it wasnt specific to 53. Nothing works.
This behaviour hints at a missing tail call optimization, so that your recursion blows the stack. A possible reason is that you have declaimed debugging optimization.
By the way, you don't need to make an explicit call to return-from. Since sum is a self-evaluating symbol, you can change this line
(return-from count-reduced-fractions sum)
to
sum
edit: Explanation of the proposed change: "sum" evaluates to its own value, which becomes the return value of the "if" statement, which (since this is the last statement in the defun) becomes the return value of the function.
edit: Explanation of declaimed optimization: You could add the following to your top level:
(declaim (optimize (speed 3)
(debug 0)))
or use the same, but with declare instead of declaim as the first statement in your function. You could also try (space 3) and (safety 0) if it doesn't work.
Tail call optimization means that a function call whose return value is directly returned is translated into a frame replacement on the stack (instead of stacking up), effectively "flattening" a recursive function call to a loop, and eliminating the recursive function calls. This makes debugging a bit harder, because there are no function calls where you expect them, resp. you do not know how "deep" into a recursion an error occurs (just as if you had written a loop to begin with). Your environment might make some default declamations that you have to override to enable TCO.
edit: Just revisiting this question, what is g? I think that you actually want to
(let ((g (gcd n d)))
;; ...
)
My guess is that there's a built-in stack depth limit with lispbox. Since Common Lisp does not guarantee tail-recursive functions use constant stack space, it's possible that every invocation of count-reduced-fractions adds another layer on the stack.
By the way, SBCL runs this algorithm without problem.
* (count-reduced-fractions 53 53 0)
881
* (count-reduced-fractions 100 100 0)
3043
As a matter of style, you could make d and sum optional.
(defun test (n &optional (d n) (sum 0)) .. )
Probably a Stack Overflow (heh).