Three physicists recently published an article showing that an inert iron bar is capable of making decisions. They attach the bar between two slot machines, repeatedly play one of the machines, pull the bar toward the machine when it winds and push the bar away from the machine when it loses. After enough plays, the […]

Three physicists recently published an article showing that an inert iron bar is capable of making decisions. They attach the bar between two slot machines, repeatedly play one of the machines, pull the bar toward the machine when it winds and push the bar away from the machine when it loses. After enough plays, the iron bar can decide whether to play one machine or the other in hopes of a better payoff. Then they say “The most important implication that we wish to claim is that the proposed scheme will provide a new perspective for understanding the information-processing principles of certain lower forms of life.” The physicists also claim the iron bar can determine the probabilities of winning on both slot machines even though it only plays one. I’m not sure I understand the article, though I will happily agree that an inert iron bar has more intelligence than the spammers that regularly bedevil my blog.

The iron bar recalls an old-time method for calculating the median of a stream; for instance, consider finding the median of a list of a thousand occurrences of the numbers 1 to 100. Initialize the median to the first number in the list. Then, at each subsequent number, increase the median by 1 if the number is higher than the current median and decrease the median by 1 if the number is lower than the current median. At the end of the list, the approximate median calculated in this way ought not to significantly differ from the actual median. This is essentially the same calculation as that of the iron bar.

Your task is to write a program that calculates approximate medians in the manner of an iron bar. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.

A recent article in the Wall Street Journal discusses the “hot hand” paradox. Basketball players especially believe in the hot hand, when making a shot you can suddenly have a hot hand and make several more shots in a row. The Wall Street Journal proposes this experiment: Toss a coin four times. Write down the […]

A recent article in the *Wall Street Journal* discusses the “hot hand” paradox. Basketball players especially believe in the hot hand, when making a shot you can suddenly have a hot hand and make several more shots in a row. The *Wall Street Journal* proposes this experiment:

Toss a coin four times. Write down the percentage of heads on the flips coming immediately after heads. Repeat that process one million times. On average, what is that percentage?

The article claims that the correct percentage is 40%, not the 50% that you would expect from an unbiased coin, and that this is proof that the hot hand exists, even from such a random source as coin flips. If you’re interested, you can read the academic article that the *Wall Street Journal* account is based on, or see discussion of it at *Hacker News*.

Your task is to write a program to confirm the 40% figure. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.

We have today a small exercise in string manipulation: Given an input string, either return a string containing the same characters but arranged to form a palindrome, or indicate that no such rearrangement is possible. Your task is to write the program that creates a palindrome. When you are finished, you are welcome to read […]

We have today a small exercise in string manipulation: Given an input string, either return a string containing the same characters but arranged to form a palindrome, or indicate that no such rearrangement is possible.

Your task is to write the program that creates a palindrome. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.

As regular readers know, I greatly enjoy problems at the intersection of recreational mathematics and number theory. Today’s exercise is an example of that. As was known to the ancient Greeks, perfect numbers such as 6 and 28 are equal to the sum of their aliquot divisors (those divisors less than the number itself); for […]

As regular readers know, I greatly enjoy problems at the intersection of recreational mathematics and number theory. Today’s exercise is an example of that.

As was known to the ancient Greeks, perfect numbers such as 6 and 28 are equal to the sum of their aliquot divisors (those divisors less than the number itself); for instance, 6 = 1 + 2 + 3 and 28 = 1 + 2 + 4 + 7 + 14. Mathematicians refer to these as P_{2} numbers the sum of the divisors, including the number itself, is twice the number.

Multiply perfect numbers are numbers such that the sum of their divisors are some multiple of the number; perfect numbers have divisor-sums twice the number, triply perfect numbers P_{3} have divisor-sums thrice, the number, and so on.

Your task is to write a program that finds multiply perfect numbers. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.

I can tell from my statistics that people like the homework problem exercises, I suppose because they are short and provide simple drill. I can also tell, from reading some of the beginning-programmer message boards, that students seem to be quicker that they used to be to post their homework problems on-line rather than figuring […]

I can tell from my statistics that people like the homework problem exercises, I suppose because they are short and provide simple drill. I can also tell, from reading some of the beginning-programmer message boards, that students seem to be quicker that they used to be to post their homework problems on-line rather than figuring out the solutions themselves, either because they are lazy or because their teachers aren’t providing sufficient help. So today we have three more homework problems:

1) Given a list of integers, return a list in which all the duplicates have been removed. For instance, given the input list [3, 2, 4, 2, 7, 3, 5, 1, 3] return the output list [3, 2, 4, 7, 5, 1].

2) Given two lists of integers, each sorted in ascending order, return a list of the integers common to the two lists; the output list must also be in ascending order. For instance, give the input lists [2, 3, 5, 5, 6, 7, 8, 9] and [1, 2, 4, 5, 5, 7] return the output list [2, 5, 5, 7].

3) Given a positive integer, determine if it is a perfect cube. For instance, the integer 125 is a perfect cube, 5*5*5, but the integer 121 is not.

Your task is to write programs that solve the three homework problems. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.

Recently, we discovered several security vulnerabilities with how both the Racket package catalog server and the Racket package client work. The vulnerabilities have now all been fixed, and we do not know of any exploitation of them. However, we encourage you to take the following steps:

- Check any packages you have uploaded to the site, to ensure that no unexpected changes have been made to them.
- Do not use the released versions of the raco pkg catalog-archive command, or the file/untar and file/unzip libraries, on untrusted inputs. If you use these tools or libraries, use a snapshot build available from http://pre.racket-lang.org/.

A total of 5 errors related to package handling were reported to us by Tony Garnock-Jones and Asumu Takikawa. Two were XSS vulnerabilities relating to handling user input in the package administration dialog. One was an error where unsanitized email addresses with path name components in them could allow a malicious user to impersonate someone else, whom they shared an email suffix with (such addresses are illegal on most mail servers, like Outlook and GMail, but not illegal in SMTP itself.) Two were errors in handling MANIFEST files and tar/zip archives, which allowed decompression to write to arbitrary locations on the file system. These last errors affected not only the server, which decompresses packages to analyze them, but also clients using the commands described above.

The relevant server-side code was fixed to appropriately sanitize user input. The package handling libraries now reject any attempts to navigate up the filesystem hierarchy, meaning that these attacks are no longer possible.

Unfortunately, due to the nature of these attacks, we cannot be sure that they were not exploited, but we have no evidence that they were. Therefore, we encourage anyone with an account to change their password, and to treat the password as compromised. Please also check your existing packages to make sure they are as you left them.

Furthermore, using the file/untar and file/unzip libraries, the raco pkg catalog-archive command, and the internal functions that manipulate packages is not safe on untrusted inputs in released versions of Racket. Since raco pkg install executes code, it is already unsafe to use on untrusted packages, but simply extracting malicious packages is also unsafe.

We have not released a new version of Racket, but encourage anyone who needs to perform these commands to use a snapshot build. The next version of Racket will be released on-schedule in October. If, however, you would benefit from a patched version of Racket 6.2.1, please let us know.

We have three simple exercises today to help beginning programmers with their homework; all three exercises have appeared on beginning-programmer forums in the last week: 1) Write a recursive function to find the sum of the first n odd integers. For instance, if n = 2, the first two odd integers are 1 and 3, […]

We have three simple exercises today to help beginning programmers with their homework; all three exercises have appeared on beginning-programmer forums in the last week:

1) Write a recursive function to find the sum of the first

nodd integers. For instance, ifn= 2, the first two odd integers are 1 and 3, and their sum is 4.2) Write a function to count the frequence of characters in a string. For instance, given the string “hello” the function should return counts of 1, 1, 2 and 1 for h, e, l and o.

3) Write functions that encrypt and decrypt messages in a Caesar cipher. Input consists of upper-case letters and spaces; the “key” is an integer giving the number of letters to shift. For instance, the message ATTACK AT DAWN with a shift of 5 is enciphered as FYYFHP FY IFBS.

Your task is to solve the three homework exercises given above. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.

Chris Webber of MediaGoblin fame will be giving two talks for the Chicago GNU/Linux User Group meeting on September 30th. The first talk will discuss the state of federation on the Web, while the second one is entitled *Functional Package Management and Deployment with Guix*:

*Tired of being stuck after an upgrade? Wish your operating system could roll forward and backwards in time, more like Git? Want a way to get really reproducible software? Or just want a better alternative to $YOUR_LANGUAGE's stressful packaging ecosystem you can run on an existing distro? And why on earth would you want something called a "symlink forest" anyway? Discover all this and more in this exciting talk about the GNU Guix project!*

If you're in the Chicago area, do not miss Chris!

GNU Guix is a functional package manager for the GNU system. The Guix System Distribution or GuixSD is an advanced distribution of the GNU system that relies on GNU Guix and respects the user's freedom.

In addition to standard package management features, Guix supports transactional upgrades and roll-backs, unprivileged package management, per-user profiles, and garbage collection. Guix uses low-level mechanisms from the Nix package manager, except that packages are defined as native Guile modules, using extensions to the Scheme language. GuixSD offers a declarative approach to operating system configuration management, and is highly customizable and hackable.

GuixSD can be used on an i686 or x86_64 machine. It is also possible to use Guix on top of an already installed GNU/Linux system, including on mips64el and armv7.

In an earlier post, I asked readers to implement the bijection *infinite* and *complete*: every node has two children. The Calkin-Wilf tree is constructed so that every rational number is assigned a unique node. Every positive rational number appears once and exactly once in the tree. The path from the root node to any selected rational is unique and can be encoded (in binary) as an integer.

Here's the unusual part:

The*dyadic fractions* are those rational numbers whose denominator is a power of 2. Numbers like 1/4, 3/8, or 11/32. These are the divisions you'd find on a ruler (in the US). Floating point numbers are usually implemented as dyadic fractions.

You can put the dyadic fractions into a binary tree as follows:

This is Minkowski's*absolutely continuous*. The function does *not* have a derivative in the usual sense.

`rational->integer`

and `integer->rational`

. John Cowan suggested the Calkin-Wilf tree as a starting point. The Calkin-Wilf tree is a rooted binary tree where the nodes (or vertices, if you like) are labeled with positive rational numbers. It is 1 ]=> (rational->integer 355/113) ;Value: 67107847 1 ]=> (integer->rational 67107847) ;Value: 355/113 1 ]=> (cwt/value *the-calkin-wilf-tree*) ;Value: 1 1 ]=> (cwt/value (cwt/left *the-calkin-wilf-tree*)) ;Value: 1/2 1 ]=> (cwt/value (cwt/right *the-calkin-wilf-tree*)) ;Value: 2 1 ]=> (cwt/value (cwt/left (cwt/right (cwt/left (cwt/left *the-calkin-wilf-tree*))))) ;Value: 4/7Ho hum. We've all seen this sort of thing before.

Here's the unusual part:

1 ]=> cwt/left ;Value 1236: #[linear-fractional-transform 1236 x/(x + 1)] 1 ]=> cwt/right ;Value 1237: #[linear-fractional-transform 1237 (x + 1)]So I can write

1 ]=> (cwt/value ((compose cwt/left cwt/right cwt/left cwt/left) *the-calkin-wilf-tree*)) ;Value: 4/7 1 ]=> (lft/compose cwt/left cwt/right cwt/left cwt/left) ;Value 1260: #[linear-fractional-transform 1260 (3x + 1)/(5x + 2)](See "Playing with Linear Fractional Transforms")

The

You can put the dyadic fractions into a binary tree as follows:

(define *the-dyadic-fraction-tree* 1) (define (dft/left node) (/ (- (* (numerator node) 2) 1) (* (denominator node) 2))) (define (dft/right node) (/ (+ (* (numerator node) 2) 1) (* (denominator node) 2))) 1 ]=> *the-dyadic-fraction-tree* ;Value: 1 1 ]=> (dft/left *the-dyadic-fraction-tree*) ;Value: 1/2 1 ]=> (dft/right *the-dyadic-fraction-tree*) ;Value: 3/2 1 ]=> (dft/left (dft/left (dft/right (dft/left *the-dyadic-fraction-tree*)))) ;Value: 9/16The next question is, what happens if I use a path derived from the Calkin-Wilf tree and use it on the dyadic fraction tree? Yes, this is a fairly random thing to try, but the trees are the same (that is, have the same structure) even if the values at the nodes are not. Either set of fractions is in a one-to-one mapping with the tree, so there is a one-to-one mapping between rational numbers and dyadic fractions.

This is Minkowski's

**?**

(question mark) function. It maps the rational numbers on the X axis to the dyadic fraction on the Y axis. It has a number of weird properties. For example, it is strictly increasing and continuous, but it is not The Standard Prelude provides functions julian and gregorian for performing date arithmetic. In today’s exercise we will extend those functions to provide arithmetic on times as well. The parameters provided to julian will be year, month, day, hour, minute, and second, and the same parameters will be returned by gregorian. Your task is to write […]

The Standard Prelude provides functions `julian`

and `gregorian`

for performing date arithmetic. In today’s exercise we will extend those functions to provide arithmetic on times as well. The parameters provided to `julian`

will be year, month, day, hour, minute, and second, and the same parameters will be returned by `gregorian`

.

Your task is to write the new `julian`

and `gregorian`

functions. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.

This is priceless. The url is http://imgur.com/tDSX24E. It says

The challenge: implement

This is in a high school math textbook in Texas.

Example 2:Is there a one-to-one and onto correspondence between integers and rational numbers?

... -4 -3 -2 -1 0 1 2 3 4 ...

... -1/4 -1/3 -1/2 -1/1 -2/4 -2/3 -2/2 -2/1 -3/4 -3/3 -3/2 -3/1

No matter how you arrange the sets, there is never one unique integer for each rational number. There is not a one-to-one and onto correspondence.

The challenge: implement

`rational->integer`

that returns "one unique integer for each rational number", and its inverse, `integer->rational`

.A friend of mine recently said to me "Don't know anything about currying except for food". I'm sure that nearly everyone who reads this blog is familiar with currying functions (and has probably curried a function within the last few hours), but it makes a good blog topic anyway.

"Currying" a function (as opposed to an entrée) is named after Haskell Curry, but he was inspired by a paper by Moses Schönfinkel, and it appears that Gottlob Frege came up with idea. So much for the name.

Pick your favorite binary function. I like "multiply", but any binary function will do. It need not be associative or commutative. As an example, imagine a

Now consider these unary functions:

This is the meta-operation we call "currying". We take a function of several arguments, decide on some fixed values for some subset of arguments, and return a new function of the remaining, unfixed arguments.

Captain Obvious has a few things to say about functions.

A function won't return a value unless you call it.

The*cardinality* of the set of return values cannot be larger than the cardinality of the set of valid arguments. Functions don't make up values. There can be *fewer* possible return values than possible valid arguments, but never more.

If two sets are different sizes, then if you try to pair up elements from each set, you'll have some left over.

If we compose two functions and the set of possible output from the first is different in size from the set of possible valid input to the second, then there will either be output from the first that the second cannot accept, or possible inputs to the second that the first cannot produce. The latter case isn't a problem, but in the former case, you'll get an error.

If you "invert" a function, its output becomes input and*vice versa*.

Since inverse functions (when they exist, that is) are functions, The same constraints on the cardinality of input and output apply, but in the other direction. If you invert a composition, then the valid arguments and results swap roles. If the cardinalities match, we're cool, but if there is a mismatch, we're in the opposite situation of the non-inverse, and what was not an error (*i.e.* accepting an input that can never be produced) becomes one (*i.e.* producing a value that cannot be accepted).

If the appropriate cardinalities never increase, you can compose two functions. If the appropriate cardinalities match, you can invert the composition.

"Currying" a function (as opposed to an entrée) is named after Haskell Curry, but he was inspired by a paper by Moses Schönfinkel, and it appears that Gottlob Frege came up with idea. So much for the name.

Pick your favorite binary function. I like "multiply", but any binary function will do. It need not be associative or commutative. As an example, imagine a

`print-to`

function that takes a document and a device.Now consider these unary functions:

(define (multiply-by-five n) (* 5 n)) (define (multiply-by-negative-one n) (* -1 n)) (define (multiply-by-thirty-seven n) (* 37 n))There is an obvious pattern here that we can abstract out:etc.

(define (make-multiply-by x) (lambda (n) (* x n)) (define multiply-by-five (make-multiply-by 5)) (define multiply-by-negative-one (make-multiply-by -1)) (define multiply-by-thirty-seven (make-multiply-by 37))Or, if we use

`print-to`

(define (make-print-to-device device) (lambda (doc) (print-to doc device))) (define print-to-inkjet (make-print-to-device the-inkjet-printer)) (define print-to-daisywheel (make-print-to-device the-daisy-wheel-printer))Note the similarity between

`make-multiply-by`

and `make-print-to-device`

.(define (make-multiply-by x) (lambda (n) (* x n)) (define (make-print-to-device device) (lambda (doc) (print-to doc device))) (define (make-<We can abstract this operation:unary> an-argument) (lambda (another-argument) (<binary>an-argument another-argument)))

(define (make-unary-maker binary-operation) (define (make-unary-operation an-argument) (lambda (other-argument) (binary-operation an-argument other-argument))) make-unary-operation)We have a pile of functions, all similar because they were created with the

`make-`

function. And the `make-`

functions are all similar because they were created with `make-unary-maker`

.This is the meta-operation we call "currying". We take a function of several arguments, decide on some fixed values for some subset of arguments, and return a new function of the remaining, unfixed arguments.

Captain Obvious has a few things to say about functions.

A function won't return a value unless you call it.

The

If two sets are different sizes, then if you try to pair up elements from each set, you'll have some left over.

If we compose two functions and the set of possible output from the first is different in size from the set of possible valid input to the second, then there will either be output from the first that the second cannot accept, or possible inputs to the second that the first cannot produce. The latter case isn't a problem, but in the former case, you'll get an error.

If you "invert" a function, its output becomes input and

Since inverse functions (when they exist, that is) are functions, The same constraints on the cardinality of input and output apply, but in the other direction. If you invert a composition, then the valid arguments and results swap roles. If the cardinalities match, we're cool, but if there is a mismatch, we're in the opposite situation of the non-inverse, and what was not an error (

If the appropriate cardinalities never increase, you can compose two functions. If the appropriate cardinalities match, you can invert the composition.

What does this have to do with currying?

I'm reading a bit about group theory and I chanced upon some exposition that was thick with comments and arguments surrounding the cardinality of various sets and subsets within the group. Once the exposition introduced a number of sets with equal cardinalities, the author pointed out that you can define an invertible function between any two sets with the same cardinality. Since the set of integers and the set of `multiply-by-`

functions have the same cardinality, you could define a function that maps integers to `multiply-by-`

functions. This isn't much of a revelation because that's what we did to get those functions in the first place. After slogging through this, I finally worked out what they were trying to say: "You can curry the binary operation." But they completely avoided the word "curry", and made arguments about set cardinality.

The next paragraph in the exposition was worse. You can curry the other argument to the binary operation. This leads to a completely different set of curried functions over a different set of arguments. Now it ultimately doesn't matter which argument you curry, when all is said and done, both arguments show up and are passed to the binary function. But all the intermediate values are drawn from different sets than if you curried the other way. It takes a very complicated argument about cardinalities to derive that either way of currying will work.

The median of an array is the value in the middle if the array was sorted; if the array has an odd number of items n, the median is the (n+1)/2’th largest item in the array (which is also the (n+1)/2’th smallest item in the array), and if the array has an even number of […]

The median of an array is the value in the middle if the array was sorted; if the array has an odd number of items *n*, the median is the (*n*+1)/2’th largest item in the array (which is also the (*n*+1)/2’th smallest item in the array), and if the array has an even number of items *n*, the median is the arithmetic average of the *n*/2’th smallest item in the array and the *n*/2’th largest item in the array. For instance, the median of the array [2,4,5,7,3,6,1] is 4 and the median of the array [5,2,1,6,3,4] is 3.5.

Your task is to write a program that takes an array of 8-bit integers (possibly but not necessarily in sort) and finds the median value in the array; you should find an algorithm that takes linear time and constant space. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.

To recap, a linear fractional transform (*lft*) is a function of this form:

(lambda (x) (/ (+ (* A x) B) (+ (* C x) D)))

Using an object-oriented extension to Scheme, I've given these functions a special print method so they look pretty. (I'm using MIT/Gnu Scheme with SOS, a CLOS-like object system. I haven't included all the code in my posts, but it should be easy for an intermediate programmer to replicate this.)

1 ]=> (make-linear-fractional-transform 1 2 3 4) ;Value 13: #[linear-fractional-transform 13 (x + 2)/(3x + 4)]But otherwise they are normal one argument functions. Since they take and return objects of the same type, you can chain them together with function composition.

(define foo (make-linear-fractional-transform 1 2 3 4)) (define bar (make-linear-fractional-transform 1 4 0 2)) 1 ]=> (compose foo bar) ;Value 14: #[compiled-closure 14 (lambda "global" #x35) #x84 #x25de16c #x3a5ea78] 1 ]=> ((compose foo bar) 1/10) ;Value: 81/203

`lft/compose`

knows to explicitly construct an lft rather than a generic closure,1 ]=> (lft/compose foo bar) ;Value 15: #[linear-fractional-transform 15 (x + 8)/(3x + 20)] 1 ]=> ((lft/compose foo bar) 1/10) ;Value: 81/203but there is no difference when you apply the composed function.

I've been distracted by group theory, so let's do something less abstract. Here is an infinite stream of linear fractional transforms.

(define lft-stream (cons-stream (make-linear-fractional-transform 0 4 1 0) (stream-map (lambda (n d) (make-linear-fractional-transform n 1 d 0)) (odds) (cons-stream 1 (stream-map square (naturals)))))) 1 ]=> (pp (stream-head lft-stream 10)) (#[linear-fractional-transform 17 4/x] #[linear-fractional-transform 26 (x + 1)/x] #[linear-fractional-transform 25 (3x + 1)/x] #[linear-fractional-transform 34 (5x + 1)/4x] #[linear-fractional-transform 33 (7x + 1)/9x] #[linear-fractional-transform 32 (9x + 1)/16x] #[linear-fractional-transform 31 (11x + 1)/25x] #[linear-fractional-transform 30 (13x + 1)/36x] #[linear-fractional-transform 29 (15x + 1)/49x] #[linear-fractional-transform 28 (17x + 1)/64x])

This is a stream of functions, so let's compose them. Imagine our function stream is `(f g h ...)`

. We want to generate the stream `(f (compose f g) (compose f g h) ...)`

1 ]=> (fold-stream lft/compose lft:identity lft-stream) ;Value 36: {#[linear-fractional-transform 37 x] ...} 1 ]=> (pp (stream-head (fold-stream lft/compose lft:identity lft-stream) 10)) (#[linear-fractional-transform 37 x] #[linear-fractional-transform 17 4/x] #[linear-fractional-transform 45 4x/(x + 1)] #[linear-fractional-transform 44 (12x + 4)/(4x + 1)] #[linear-fractional-transform 43 (19x + 3)/(6x + 1)] #[linear-fractional-transform 42 (160x + 19)/(51x + 6)] #[linear-fractional-transform 41 (1744x + 160)/(555x + 51)] #[linear-fractional-transform 40 (23184x + 1744)/(7380x + 555)] #[linear-fractional-transform 39 (10116x + 644)/(3220x + 205)] #[linear-fractional-transform 38 (183296x + 10116)/(58345x + 3220)])

Let's apply these transforms to a number. 42 is random enough.

1 ]=> (pp (stream-head (stream-map (lambda (transform) (transform 42.0)) (fold-stream lft/compose lft:identity lft-stream)) 10)) (42. .09523809523809523 3.9069767441860463 3.0059171597633134 3.16600790513834 3.137337057728119 3.1423312358203845 3.141464985588458 3.1416146775443905 3.1415888593191537)That looks familiar. We'll pick a point further on in the stream.

1 ]=> (stream-ref (fold-stream lft/compose lft:identity lft-stream) 20) ;Value 48: #[linear-fractional-transform 48 (2166457145737216x + 48501417558016)/(689604727481670x + 15438480702645)] 1 ]=> ((stream-ref (fold-stream lft/compose lft:identity lft-stream) 20) 1.0) ;Value: 3.1415926535898056This stream of functions are functions that approximate π. Each element in the stream is a function that is a better approximation of π than the last.

1 ]=> (stream-ref (fold-stream lft/compose lft:identity lft-stream) 10) ;Value 51: #[linear-fractional-transform 51 (3763456x + 183296)/(1197945x + 58345)] 1 ]=> (define foo (stream-ref (fold-stream lft/compose lft:identity lft-stream) 10)) 1 ]=> (foo 0.0) ;Value: 3.1415888250921244 1 ]=> (foo 1.0) ;Value: 3.141593103503172 1 ]=> (exact->inexact (foo 'infinity)) ;Value: 3.1415933118799275Ok, let's subtract off that three.

(define (make-lft-subtract n) (make-linear-fractional-transform 1 (- n) 0 1)) 1 ]=> (lft/compose (make-lft-subtract 3) foo) ;Value 54: #[linear-fractional-transform 54 (169621x + 8261)/(1197945x + 58345)] 1 ]=> ((lft/compose (make-lft-subtract 3) foo) 42.) ;Value: .14159330668296408And multiply by ten

(define (make-lft-multiply n) (make-linear-fractional-transform n 0 0 1)) 1 ]=> (lft/compose (make-lft-multiply 10) (make-lft-subtract 3) foo) ;Value 55: #[linear-fractional-transform 55 (339242x + 16522)/(239589x + 11669)] 1 ]=> ((lft/compose (make-lft-multiply 10) (make-lft-subtract 3) foo) 42.) ;Value: 1.4159330668296406and now the next decimal digit is in the ones place. If we repeat this process, we'll generate the decimal digits of our approximation to π one at a time.

1 ]=> ((lft/compose (make-lft-multiply 10) (make-lft-subtract 3) foo) 42.) ;Value: 1.4159330668296406 1 ]=> ((lft/compose (make-lft-multiply 10) (make-lft-subtract 1) (make-lft-multiply 10) (make-lft-subtract 3) foo) 42.) ;Value: 4.159330668296407 1 ]=> ((lft/compose (make-lft-multiply 10) (make-lft-subtract 4) (make-lft-multiply 10) (make-lft-subtract 1) (make-lft-multiply 10) (make-lft-subtract 3) foo) 42.) ;Value: 1.5933066829640692We'll define a

`composition`

as a data structure with an lft and a `promise`

(delayed evaluation) to provide more lfts to compose. Operations on a `composition`

will work on the lft and try to avoid forcing the promise if possible. If the lft isn't a good enough approximation, we force the promise, get a new lft, and create a new `composition`

. (define-class (<lft-composition> (constructor make-lft-composition (linear-fractional-transform promise))) () (linear-fractional-transform define accessor accessor composition-transform) (promise define accessor accessor composition-promise)) (define (composition/refine lft-composition) (let ((lft (composition-transform lft-composition)) (lft-stream (force (composition-promise lft-composition)))) (make-lft-composition (lft/compose lft (head lft-stream)) (cdr lft-stream))))Getting the integer part of a

`composition`

involves getting the integer part of the transform, if possible, and if not, refining the composition until it is possible. `composition/integer-and-fraction`

returns two values: the integer extracted, and the final composition remaining after any refinement steps and after subtracting off the integer.(define (composition/%integer-part lft-composition) (lft/integer-part (composition-transform lft-composition))) (define (composition/integer-and-fraction lft-composition) (let ((integer (composition/%integer-part lft-composition))) (if (not integer) (composition/integer-and-fraction (composition/refine lft-composition)) (values integer (make-lft-composition (lft/compose (make-linear-fractional-transform 1 (- integer) 0 1) (composition-transform lft-composition)) (composition-promise lft-composition))))))We'll create a stream of digits by peeling off the integer parts and multiplying the fraction by 10.

(define (composition->digit-stream c radix) (receive (ipart fpart) (composition/integer-and-fraction c) (cons-stream ipart (composition->digit-stream (make-lft-composition (lft/compose (make-linear-fractional-transform radix 0 0 1) (composition-transform (force fpart))) (composition-promise (force fpart))) radix)))) (define foocomp (make-lft-composition (head lft-stream) (cdr lft-stream))) 1 ]=> (stream-head (composition->digit-stream foocomp 10) 50) ;Value 204: (3 1 4 1 5 9 2 6 5 3 5 8 9 7 9 3 2 3 8 4 6 2 6 4 3 3 8 3 2 7 9 5 0 2 8 8 4 1 9 7 1 6 9 3 9 9 3 7 5 1)

Pierre de Fermat issued these two challenges in 1657: First, find a cube that, when increased by the sum of its aliquot divisors, becomes a square; for instance, 73 + (1 + 7 + 72) = 203. Second, find a square that, when increased by the sum of its aliquot divisors, becomes a cube. I […]

Pierre de Fermat issued these two challenges in 1657: First, find a cube that, when increased by the sum of its aliquot divisors, becomes a square; for instance, 7^{3} + (1 + 7 + 7^{2}) = 20^{3}. Second, find a square that, when increased by the sum of its aliquot divisors, becomes a cube. I would guess that Fermat knew the answer to the first challenge but not the second.

In the days before computers, challenges such as this were frequently issued by one mathematician or group of mathematicians to their competing colleagues; for instance, the French mathematicians might challenge the German mathematicians. Once the challenge was met, the solving group would issue a new challenge to the original challengers. It was considered un-gentlemanly to issue a challenge to which you did not have a solution, though Fermat was probably respected enough to get away with it. Times have changed.

Your task is to write programs that find solutions to the two challenges. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.