Friday, 9 December 2016

Plots have I laid, inductions dangerous

Time to do some F#.

First I want a function that will tabulate a function f.

f is to be a function of two floats x and y returning a float. The table is to operate over an x-axis range and a y-axis range, each described by a tuple of floats.  So here is a sample function of the type I mean:

let testfun (x:float) (y:float) =
    let r = sqrt ((x * x) + (y * y))
    if r < 2.0
        if r < 1.0
        then 7.0
        else 4.0

My tabulate function is to return a two-dimensional array of floats.  Here it is:

let tabulate funct (xrange : (float*float)) (yrange : (float*float)) : float[,]=
    let x0 = fst xrange
    let dx = (snd xrange - fst xrange) / 50.0
    let y0 = fst yrange
    let dy = (snd yrange - fst yrange) / 50.0
    Array2D.init 51 51 (fun i j -> funct (x0+(float i * dx)) (y0+(float j * dy)))

The function Array2D.init takes the size of the two dimensions of the array and a function that will populate each element in the array, given the indices I and j. I'm breaking my ranges into 50 parts so I want 51 elements in each direction.

Now to project this table of values as in isometric type sheet: create a new array of the same size but here each element is a tuple of values p and q that represent screen coordinates. p works down from the top left and q works across. So p and q depend on the index i and j, and p also depends on the value of the array that I've passed through.  I've scaled the value by 10.0 pixels quite arbitrarily. The grid is drawn by going right 5 pixels per cell and either up or down by 3.5 pixels for p and q axis, so:

let project (valueTable : float [,]) : (float * float)[,] =
    Array2D.init 51 51
        (fun (i:int) (j:int) ->
            let p = (float i * 5.0) + (float j * 5.0) + 20.0
            let q = (float i * 3.5) - (float j * 3.5) + 300.0 - (valueTable.[i,j] * 10.0)

Right, now I want to plot out the projected table as an SVG element. After some research it looks like this is the thing to do:

let plot (a:(float * float)[,]) : unit =
    use file = System.IO.File.CreateText("plotout.svg")
    fprintfn file """<svg xmlns="" version="1.1">"""
    for j in 0..49 do
        for i in 0..49 do
            fprintf file """<polygon fill="#FFFFFF" """
            fprintf file """stroke="#000000" stroke-width="1" points="""
            fprintfn file "\"%.2f,%.2f %.2f,%.2f %.2f,%.2f %.2f,%.2f\" "
                (fst a.[i,j]) (snd a.[i,j])
                (fst a.[i,j+1]) (snd a.[i,j+1])
                (fst a.[i+1,j+1]) (snd a.[i+1,j+1])
                (fst a.[i+1,j]) (snd a.[i+1,j])
            fprintfn file """/>"""
    fprintfn file """</svg>"""

The SVG document contains a polygon element which has a fill colour and a stroke width and colour and a list of points - each point is represented by a two floats separated by a comma. For each element i, j I'm drawing a four sided shape with the points from i,j - i+1,j - i+1,j+1 - i,j+1.

So finally to tabulate and plot my test function in the range -3 to 3:

let main () =
    (tabulate testfun (-3.0, 3.0) (-3.0, 3.0)) |> project |> plot

Then you can open the resulting file in the browser:

This looks a bit rough round the back of the raised area.  Really I need to plot starting from the cells that are furthest away and then working forward, so get the hidden ones properly hidden. Still, nice first try.

Friday, 25 November 2016

Random Questions

  • What is "Black Friday", and why?
  • What is a "comfort zone" and where do I get one?  Can I rent or do I buy it?
  • Is a "steep learning curve" one where I get from the bottom to the top quickly and easily or one where the route from the bottom to the top is difficult? (It's a lousy metaphor if it works two contradictory ways).
  • How much exactly is "most if not all"? Most? All? Which? Either? On the same note how hard is "difficult if not impossible"? So difficult it's effectively impossible? Or very difficult but not actually impossible? Or either difficult or impossible but you don't know which? Why not find out and tell us instead of leaving us dangling with an "if"...? What if I said, "The answer to your question is yes if not no"... How informed would you be?

Friday, 4 November 2016

F Sharp for Pleasure and well just pleasure really

The language F# has its origins at Microsoft and is now available in the latest versions of Visual Studio - but looking at I see there is an option to use F# on Linux.

But first you need Mono for it to run on... which I did basically by following the instructions on the Mono site.  The instructions are nice and clear so I resist the inclination to copy them here.

Then to test.  Create a file called hello.cs containing this code:

using System;

public class HelloWorld
    static public void Main ()
        Console.WriteLine ("Hello Mono World");

Then on the command line (you can come out of super user mode now) compile with this command:

mcs hello.cs

This creates a file called hello.exe that you can execute:

$ mcs hello.cs
$ ls h*
hello.cs  hello.exe
$ ./hello.exe
Hello Mono World
$ mono hello.exe
Hello Mono World

You can execute with the command mono but I didn't spot this and I find you can invoke the hello.exe directly. What have I just done? Blimey I've typed in and compiled a C# program almost without realising it.

So anyway that does demonstrate that Mono is installed... jolly good.

So I next need

apt-get install fsharp

Looks ok.  This installs fsharpc (the compiler) and fsharpi (the interactive REPL)

Possibly at this point... install Visual Studio Code...?

OK go on then.

Had to log off and log on as administrator to get this to work. It's a download from the Visual Studio Code web site.

However this seems to be in place.  Then you add the F-Sharp mode to the editor by going

ext install Ionide-fsharp

Then you select the right one, opt to install and then activate.

So that was very successful - the F Sharp site and the Mono site have excellent instructions for getting set up.

Now also there is an F-Sharp mode for Emacs.  I'll look into that another day.

Thursday, 3 November 2016

Crossing the Bridge

And having started from that left hand end of the bridge in an engineering role I have tried to explore some of the delights that await as you cross to the other side.

One of the odd pleasures of this challenge is seeing how difficult things become clear... but if anything even more delightful is to find how obvious things start to become problems.

A processor has executed an instruction. What can it do next? Just three things.

It can move on to the next instruction: and so the idea of a sequence is natural and obvious.

It can jump back to a previous instruction. And so the idea of a loop is present, but not yet obvious. We know that to jump back just anywhere is the road to madness. The jump has to be educated, trained to fit into the pattern. I write lots of flowcharts. To apply the pattern I have a rule that jumps back from the main flow must go to the right (anticlockwise) and furthermore no line is allowed to cross another.  So this is allowed:

But this is not:

Stick to the discipline and you have created the logic of the loop from the potential chaos of the jump.

And what is the other option? The processor can jump forward. Therefore it has opted to omit some part of the process, we are creating the conditional if / else construction. Here again my jumps need to submit to the discipline: all jumps down must go to the right, and no line is allowed to cross another. So this is allowed:

But not this:

This is what a proper if / else brings out in a higher level language.

And so given the sequence, the loop, and the conditional, we have the essence of structured programming. Everything we need.

What could be more obvious?

But then we start to wander across this enchanted bridge and soon we discover mysteries.

I clearly remember when I was learning Scheme, just about the first thing I wanted to write was the table of Celsius to Fahrenheit conversion from somewhere near the start of Kernighan & Ritchie. And I sat there thinking... just a minute, hold it right there, how exactly do I write a FOR loop? Surely there's got to be a way to write a FOR loop, otherwise...

Then of course you encounter the delights of looping by recursion, and the more mature delight of realising that your loops dissolve in functions that operate on collections directly, you discover MAP and FOLD and FILTER and so on. So the loop, which seemed so obviously essential to programming, becomes a stage that you leave behind. Odd. Disturbing and yet illuminating.

How truly it is written, In the search of the Way, every day something is left behind (Tao Te Ching Ch.48)

Next you discover pattern matching and see how a function can fork according to the structure of its arguments and you start to realise that you can make conditions without going through IF... in fact do you need IF at all? Can all your decisions be made on the basis of pattern matching with the odd guard or two here and there? Does IF go in the bin next to LOOP?

Then the final stage of your enlightenment comes when you discover that the sequence has now... gone. That most obvious thing of all, the increment of the program counter, becomes a problem that the Masters have to invoke arcane spells from mathematics to solve.

It turns out that even

is no longer allowed...

Wednesday, 26 October 2016

Programming Languages

Programming languages are miraculous. Somehow they overcome Cartesian dualism. They make matter and form work together. They make body and soul act in unison. They bridge the ontological gulf between the material realities of engineering and the abstract eternal truths of mathematics. And various different languages occupy different places on that bridge,like this:

Historically the two ends of this bridge have been built by different people working in different parts of the computing world. However we are now in an interesting time because the two ends are starting to meet at last.

What have I put up there at the joining place?  F#.  Hmm.

Tuesday, 18 October 2016

On Pausing Before Pressing Alt Shift F10

Whose code this is I think I know
His source is all in Github though
He will not see me waiting here
In case the buffers overflow.

My IDE has deemed it queer
To put a breakpoint just in here
Outside the brackets in white space -
Is that invalid?  Never fear.

It writes a wriggly underline
To indicate it might incline,
All things considered, to demur.
You have your viewpoint, I have mine.

The arguments are all in scope
Recursion promises to cope
The tail call's optimised, I hope
The tail call's optimised.  I hope.

Friday, 9 September 2016

Music While You Code - Really?

I just finished listening to Episode 44 of the Coding Blocks podcast (a true epic - well done guys) and - wait a minute: did you really say "we listen to music as we write code"? (16 minutes in)  Really?  How do you do that? 

I find that any amount of music around me pretty soon diverts all my attention and all power of concentration.  If music is going in my ears at all then I do not have the option to not listen!  How would I listen to music while I am writing code?  Those are the exact same neurons that I use for both tasks!

In fact I have a theory that if you make a habit of trying to concentrate on any mental work while there is also music playing, then little by little you are training your nervous system to treat the sound of music as noise that has to be filtered out of your input system.

In time surely this must erode your ability to respond to music fully when you are able to give it your full attention.  If you take music seriously then surely you don't want that to happen?

Wednesday, 31 August 2016

Now that's what I call a project

Another nice link from the Programming Throwdown boys: a Quartz article explaining that the source code for the Apollo Guidance Computer developed for the lunar landing project back in the sixties has found its way onto Github.

There's a picture of the directory of software engineering Margaret Hamilton (another heroine for the gallery) standing next to a stack of source code printouts.  The stack is very nearly as tall as she is. Now that's what I call a Project. I might just print this out and frame it.

I've written plenty of assembler code over the years.  Our most complicated selector system would fill about half of one of those binders, and I am generous with comments.

I am just old enough to remember the lunar landings. I don't imagine anything quite like that will happen again.

The nearest is the marvellous results they get from the unmanned probes that have been sent to comets, under the clouds of Venus, and recently out to frosty Pluto (especially brilliant).

But I can't see actual people ever going out there, even to the Moon.

There has been talk of manned expeditions to Mars - - but the resources required for that project would be massive even compared to what was spent sending men to the Moon. Who has that kind of money available, and why would they spend it on space travel?

Back in the sixties it was different - we were in the Cold War: the capitalist nations felt they were under real threat of being overtaken by the rise of communism, and any expenditure was based on that fear.

Neil Armstrong was sent to the Moon because otherwise the Soviets might get there first.  After all, they sent the first satellite, and the first man and the first woman into space, and the first probe round the back of the moon, they are just the ones I can think of off the top of my head.  And the first dog.

But now of course the Soviets are history, that panic is over, the incentive is gone.

Granted, we do have the technology to send people to the planet Mars.  We also have the technology to go out into the Sahara and build some more pyramids.  But we are not going to, because we have no reason to. 

Monday, 13 June 2016

The Real World

In the Real World, While and Until don't necessarily mean what programmers take them to mean.

I had a discussion with someone with a card that said, Valid until June 2016.  Does than mean it is valid until the start of June 2016 and then stops being valid?  No, because this is the inclusive "until".   It stops being valid after the point it is valid until.  This works with dates because it is unambiguous what is "after" June 2016.

Same with my weekly bus ticket.  Where it says it is valid until Tuesday that means including Tuesday and then stops being valid on Wednesday.  In code you would write this as "valid until date > Tuesday" not "valid until date = Tuesday".

People in Hull often use the word While where you might expect Until.  For example, you might hear "it was posted on Monday so it won't arrive while Thursday".

Wednesday, 16 March 2016

New Heroine

Interesting... following a link from Lambda The Ultimate to this Model View Culture article

I had no idea that the Sacred Language itself (ie Assembler) was created by a woman, Kathleen Booth.  So I have a new heroine to put next to Grace and Ada.

Unlimited Respect!

Tuesday, 8 March 2016

A lot to learn

A change is as good as…

I've put Linux on the laptop.  Specifically, Mint 17.3, from the cover disk on the February issue of Linux Format magazine.  This went on amazingly quickly and, er, just works.  I've plonked Emacs on here as well and Haskell and Git.

I went through a humiliating evening trying to create a restore disk for Windows 7 and for some reason this wouldn't work.  There were workarounds that involved logging in with increasing user permissions but in the end I thought I'd risk it and load Ubuntu anyway, with the aim of dual booting with Windows 7.  However the Ubuntu installation crashed and took access to Windows with it.  I could still run Linux from a live CD but boot nothing from the hard disk.  Serves me right. Somebody smarter than me could perhaps have got Windows back.  But then I thought, hang on, just how much would I miss the Windows stuff if it all went away?  So I stuck the disk in and said to Mint, go ahead, all yours, and here we are. Looks good!  And there is a lot to learn...

Friday, 12 February 2016

So right then what next?

Right then what next? Do I look at Elm and start doing things in a browser? Nothing I do in my day job goes anywhere near the web. But if your next language does not make you think differently then why bother? What about Elixir? That is back in the days of Erlang. If you want types in Erlang then there is a separate tool that does this for you. But surely that's not the same thing as having proper types in your language. I am sold on the idea that you need a static type system. Also I am sold on the idea that the either and maybe types are the billion pound solution to the billion pound mistake. Why would anybody not want static types? Why would anybody not want pattern matching? You can or I should say you must use Dialyzer. Who thought of that name? I can't read the word without a mental image of pipes pumping blood around. Aaarg. Elixir looks like it has lots of good ideas. And you get all the concurrency capability of Erlang. But I like the lisp way of writing, where you have one opening bracket at the start of the idea and a close bracket at the end of the idea. What is the problem? Why would you not want that? If it's not there in the code then you have to think where each part starts and stops. You either write the brackets or you have to imagine them all the time. And it lets you have hyphens in object names which is the sanest way to write multi-part identifiers. You can use hyphens in Cobol too. Using underlines is ugly and using capitals midway through the word is not much better and gets much worse if the identifier starts with a lower case letter. That is an idea worthy of the camel that they say invented it. In Basic on the Sinclair Spectrum you could have spaces in identifiers - beat that. Do I say now this is the time to do the deep dive into Haskell that I have been postponing all along? In honesty are all other languages just attempts to postpone the day you have to learn Haskell? So far with all this stuff I have just been moving across the face of the waters. Hmm. And I've got Smalltalk loaded on a machine somewhere. And there's Scala. Scala looks suspiciously enterprise to me. But it's supposed to be scalable so maybe there's a lighter side to it. I note there is a book specifically about functional programming with Scala. So here we are floating above the JVM again. Java is another one I've not touched, though there's no reason to go there now that I can think of. When I looked at the idea of embedding a high(er) level language in bingo equipment I thought Forth would be ideal. Only Scheme comes close. In fact I still think Forth would be ideal. How much does a clarinet cost, and how long would it take to get reasonably good at it? There again there's Clojurescript now for your browser which ties in directly with Clojure which I quite liked. They're are doing all kinds of clever stuff. When you have to call your solution Om you know enlightenment is near. Either that or madness. So right then what next?