My Mailbag

February 7, 2020

I had two interesting emails from readers this week. I’ll discuss both of them, but suppress the names of the writers; they can identify themselves in the comments below if they wish.

One writer saw Johnny Ball’s video about Russian Multiplication on Numberphile and suggested it would make a good exercise. Indeed it would; in fact, we have already done it twice ([1] [2]).

Another writer suggested that the compose function in the Standard Prelude should return the identity function if called with no arguments, rather than reporting an error. That is, of course, correct; my apologies for the bug.

Your task is to write programs to perform russian multiplication and compose functions, as suggested 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.

Advertisement

Pages: 1 2

2 Responses to “My Mailbag”

  1. Gambiteer said

    Should compose with no arguments return a function like (lambda args (apply values args))?

  2. Daniel said

    Here’s a solution in Python.

    def multiply(a, b):
        assert a >= 0 and b >= 0
        result = 0
        while a:
            if a & 1: result += b
            a >>= 1
            b += b
        return result
    
    for x in range(10):
        for y in range(10):
            assert x * y == multiply(x, y)
            assert x * y == multiply(y, x)
    
    print(multiply(9, 13))
    print(multiply(7, 13))
    
    def compose(*args):
        def fn(x):
            for arg in reversed(args):
                x = arg(x)
            return x
        return fn
    
    rev_sort = compose(list, reversed, sorted)
    identity = compose()
    l = [3, 4, 6, 1, 0, 7, 2, 8, 5, 9]
    
    print(rev_sort(l))
    print(identity(l))
    

    Output:

    117
    91
    [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
    [3, 4, 6, 1, 0, 7, 2, 8, 5, 9]
    

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: