Category Archives: General

Functional Programming for Under-4s

My grandson has recently learned to count, so I made a set of cards we could ‘play numbers’ with.

We both played. I showed him that you could write ‘maths sentences’ with the ‘and’ and the ‘is’ cards. Next time I visited, he searched in my bag and found the box of numbers. He emptied them out onto the sofa and completely unprompted, ‘wrote’:

I was ‘quite surprised’. We wrote a few more equations using small integers until one added to 8, then he remembered he had a train track that could be made into a figure-of-8 , so ‘Arithmetic Time’ was over but we squeezed in a bit of introductory set theory while tidying the numbers away.

From here on, I’m going to talk about computer programming. I won’t be explaining any jargon I use, so if you want to leave now, I won’t be offended.

I don’t want to take my grandson too far with mathematics in case it conflicts with what he will be taught at school. If schools teach computer programming, it will probably be Python and I gave up on Python.

Instead, I’ve been learning functional programming in the Clojure dialect of Lisp. I’ve been thinking for a while that it woud be much easier to learn functional programming if you didn’t already know imperative programming. There’s a famous text, known as ‘SICP’ or ‘The Wizard Book’ that compares Lisps with magic. What if I took on a sourceror’s apprentice to give me an incentive to learn faster? I need to grab him “to the age of 5”, before the Pythonista get him.

When I think about conventional programming, I make diagrams, and I’ve used Unified Modelling Language (UML) for business analysis, to model ‘data processing’ systems. An interesting feature of LIsps is that process is represented as functions and functions are a special type of data. UML is designed for Object Orient Programming. I haven’t found a way to make it work for Functional Programming (FP.)

So, how can I introduce the ideas of FP to a child who can’t read yet?
There’s a mathematical convention to represent a function as a ‘black-box machine’ with a hopper at the top where you pour in the values and an outlet at the bottom where the answer value flows out. My first thought was to make an ‘add function’ machine but Clojure “treats functions as first-class citizens”, so I’m going to try passing “+” in as a function, along the dotted line labelled f(). Here’s my first prototype machine, passed 3 parameters: 2, 1 and the function +, to configure the black box as an adding machine.

In a Lisp, “2 + 1” is written “(+ 2 1)”.
The ‘parens’ are ‘the black box’.

Now, we’ve made our ‘black box’ an adder, we pass in the integers 2 and 1 and they are transformed by the function into the integer 3.

We can do the same thing in Clojure. Lisp parentheses provide ‘the black box’ and the first argument is the function to use. Other arguments are the numbers to add.

We’ll start the Clojure ‘Read Evaluate Print Loop’ (REPL) now. Clojure now runs well from the command line of a Raspberry Pi 4 or 400 running Raspberry Pi OS.

$ clj
Clojure 1.11.1

user=> (+ 2 1)
3
user=>

Clearly, we have a simple, working Functional Program but another thing about functions is that they can be ‘composed’ into a ‘pipeline’, so we can set up a production line of functional machines, with the second function taking the output of the first function as one of it’s inputs. Using the only function we have so far:

![[5compose–IMG_20221116_135501768-2.jpg]]

In Clojure, we could write that explicitly as a pipeline, to work just like the diagram

(-> (+ 1 2) (+ 1))
4

or use the more conventional Lisp format (start evaluation at the innermost parens)

(+ (+ 1 2) 1)
4

However, unlike the arithmetic “+” operator, the Clojure “+” function can
add up more than 2 numbers, so we didn’t really need to compose the two “+” functions. This single function call would have got the job done:

(+ 1 2 1)
4

SImilarly, we didn’t need to use 2 cardboard black-boxes. We could just pour all the values we wanted adding up into the hopper of the first.

Clojure can handle an infinite number of values, for as long as the computer can, but I don’t think I’ll tell my grandson about infinity until he’s at least 4.

Advertisement

Shop cop

Words interest me. As I’ve been getting interested in green woodworking and the appropriate tools, I’ve become more aware of the US term “shop”. A few days ago, in a discussion of why America is lagging behind on lower level tech education, someone suggested schools needed to reintroduce ‘shop’, to get kids interested in designing and making things. I think young Brits would know this as ‘Design Technology, Resistive Materials’. I did ‘Woodwork’ and ‘Metalwork’.

America takes its cars ‘to the shop’ because their ‘garages’ are being used as ‘car parks’. Obviously, it means ‘workshop’.  A shop where you buy work, a service instead of a product, as you walk down main street. Not at all like a job-shop in Britain where we try to sell spare labour to employers, or shop for jobs, if you prefer.

I came across a meaning from the world of share trading. A stock may be ‘shopped’ – actively sold. I think we’re finally getting to the meaning. A shop is a place (real or virtual) where goods, services and labour are traded, in either direction. A market stall. I almost wrote “store” but stores are where you keep things before selling our when they haven’t sold.

I was slightly side-tracked by coppers, copping criminals and taking them to the cop shop, trading their liberty for their crimes. My government assures me that if I haven’t committed a crime I won’t cop it. I wish I believed them. That’s the cost of lying in a market that depends on trust and information. Their share price is down.

Suits you?

Last night I went to a ‘Product Tank Birmingham’ workshop on ‘Empathy Mapping’. As an exercise, we looked at ‘a product meeting group’ and tried to identify its customers. There was a brief discussion about ‘Product Owners’ (from agile software development) and ‘Product Managers’ who often have a more marketing-led approach. Someone then commented on what ‘Product people’ think. I found I didn’t agree. I reflected on the difference between Product Owners (in this context: me), who care about giving people the product they want and Product Managers, who seem to care more about people’s relationship with the product.

I realised there is a half-way house and I have not, to date, worked in it. My experience in agile software development has been about “custom” development of software products for small teams with a shared view of what they want. I’ve realised for a while that my experience is very different to those Product Owners who have to develop a more generic product to ‘optimise’ across a set of potential or actual customers who have differing needs. There is an extra role there which is far more like my understanding of Product Management. I think the key difference is the need to correctly judge the closeness of fit needed to achieve mass market appeal vs the bespoke tailoring trade that I’ve worked in.

Early in my career, I worked as a programmer on a software package for pharmaceutical companies. We coded to specifications provided by 2 people, a salesman and our technical manager, who both travelled the world visiting customers’ sites. Looking back, I think the salesman was much better at identifying the features that would be valued by most customers. Is marketing USEFUL?

RUNOFF another copy?

I was telling a story about my first job a couple of days ago. I was an ‘applications programmer’ at Cambridgeshire College of Art and Technology. There was an Argentinian lecturer who knew our systems. He asked if his wife could use the computer centre facilities to write up her research thesis during the Summer holidays. We were casual users of a text processing ‘tagging language’ for documentation. It was called DSR, Digital [Equipment Co.] Standard Runoff, so my colleague John suggested she used that. The ‘typing department’ had some fancy new ‘word processors’ (I think they were Wang) but we didn’t have any authority over them and wouldn’t be able to help her with problems. We also had doubts about whether they had the capacity for a whole thesis.

So it was that John and, in his absence, I provided occasional help to a charming, intelligent Argentinian woman during the outbreak of the Falklands War in 1982, while the British press ramped up the hatred of British idiots against the entire Argentinian nation. She was the first Argentinian I’d ever met and it was the first time I had any indication that fascism could also infect the UK or was personally shamed by the state of our newspapers. I remember us scooping up some hate-filled tabloid front page and dumping it, seconds before our guest arrived.

In later jobs I learned of Unix roff, nroff and troff and came to assume that Runoff was DEC’s version of the Unix tools. Today I discovered that isn’t true. DEC’s Runoff came from the common ancestor of the Unix tools, Runoff on CTSS then Multics (1964.)
“types out text segments in manuscript form.”

https://en.wikipedia.org/wiki/TYPSET_and_RUNOFF

CTSS was also the original home of LISP, ALGOL and the text editor QED, the predecessor of ed, vi and vim.

Model Software

Today, I had to stop myself writing “solving the problem” about developing software. Why do we say that? Why do software people call any bounded area of reality “the problem domain”?

My change of mind has been fermenting for a while, due to modelling business processes, learning about incremental, agile software development and more recently writing and learning functional programming. In the shower this morning, I finally concluded that I think software is primarily a modelling medium. We solve problems using the models we build.

Wanting to create another first-person shooter game or to model the fluids in a thermo-nuclear reactor are challenges, not problems. We build models of systems we have defined and the systems don’t even have to be real. I read a couple of days ago that a famous modern philosopher said our world is made of both reality and our ideas. Assuming the computer hardware is real, the software can model either reality or our imagination; our chosen narrative.

‘Digital’ gets everyone working with software models instead of reality. Once everyone lives inside the shared model, when does it become our reality?

Or when did it?

Idea-bending minds, mind-bending ideas

Long ago, I took 4/9ths of an undergraduate physics degree, along with 4/9ths computer science and 1/9th mathematics. Having had little or no contact with physics in the intervening years, I’ve started to do some light reading about relativity in the last couple of years. This week, I came across a tip on Quora * to a fellow traveller in space-time: “stop thinking of the speed of light as a number”. Erm… WHAT?! As every school child knows, the maximum  speed of light (or any other form of electromagnetic radiation) in a vacuum is about 600,000 Km/s. That sounds like a number to me. The problem with speed in Einstein’s relativistic model of reality though, is that distance and time get very weird. That makes them hard to think about, so the advice was to ignore what we think we know and look at things in a new way.
[* – I’ll add an acknowledgement to the author of  the comment on Quora, if I ever find it again. It took me a while to understand what I’d read. ]

I’m not sure I was entirely paying attention when I studied physics last time. I don’t remember anyone explaining the precise nature of the the scientific method, or indeed what physics actually is; that’s metaphysics. This time around I see science as the process of understanding how nature works, using evidence rather than guessing then arguing the case for your beliefs. That is philosophy, or a religion. Physics, in particular, is about observing reality and working out what the rules are. It is NOT about saying why things happen. As science was becoming formalised, it was known as ‘natural philosophy’ i.e. philosophy that refers to evidence from nature.

Einstein’s Theories of Relativity say that matter and energy are equivalent. His equation of mass-energy equivalence records the relationship between the alternative mass and energy forms of matter. It is a very well known equation, even with people who have no idea what it refers to.

The form of the equation we are most familiar with is

E = mc²

E is the concentrated energy contained in a mass, m. E is a much bigger number than m because we know that c is a big number AND it’s squared.

This equation can be re-arranged to a form I don’t remember seeing or taking note of before:

c = √(E/m)

This new way (at least to me) of looking at this century old theory says that c is related to the ratio between the Energy and mass of an object. This ratio stays the same, even as space-time expands or contracts, according to the General Theory of Relativity. The recent confirmation by the LIGO project of gravitation waves that also travel at c, were also predicted, so this gives extra weight to the theory

I’ve realised that physics often relates things to each other, without saying which is the ‘fundamental thing’. Does gravity bend space-time or is the curvature of space-time what causes gravity? The equations work either way.

John Archibald Wheeler said it a different way: “Space-time tells matter how to move; matter tells space-time how to curve” and matter can be converted to energy, energy to matter.
Continue reading Idea-bending minds, mind-bending ideas

I’m through the Digital looking-glass

I think I’ve ‘got’ for the first time what the “DIGITAL” thing is.

I’ve been searching to find the meaning of the phrase “digital transformation”, which I assumed encompassed a change from ‘analogue’ to ‘digital’. I finally understood yesterday – that’s not what it’s really about.

The transformation happened slowly to me, over most of my life. My first programming was planned on paper then character boxes were filled-in with a graphite pencil on cards. They were shipped by road to a punch machine that punched the binary codes onto the cards which were then were fed into a computer by operators I never saw. A week later I got some printout back, usually telling me what had gone wrong.

Soon after arriving at university, I had access to GEORGE 3’s Multiple On-line Programming system: a terminal. I used a line editor to create a card-image file which was stored on disk then later submitted to the batch queue. Undergraduates were only allocated space to store one program at a time. There wasn’t room to keep things permanently on-line because of the price of disk space. Some of the research students still walked around with boxes of cards. It was easy to copy a card-stack on one of the card punches and keep it in a safe place. They could probably store more code that way.

I’ve been mostly digital since the 1970s but I saw my digital world as a binary virtualisation of a physical medium. I moved very slowly from dependence on physical to online-only artifacts which had always been representations of digital data.

I realised yesterday that most people have only recently moved their business objects: files, documents, photographs, drawings, 3D-models and social network connection information into the digital realm – from atoms to bits. That frees those objects from their bindings at a single, fixed physical location, leaving them to roam in more than the 3 dimensions of our visualisable reality. This paradigm shift has suddenly hit many without warning, like a revolution, whereas I experienced it as a series of small increments. I’ve been greatly underestimating how disorienting it has been for other industries to reluctantly release their tight grip on physical objects and how worrying it may be for those still facing the cultural adjustment.

I remembered the other day that I used to jump off a shed roof at 5 years old. I could see the spot where I would land. I can’t imagine throwing myself out of a plane into free-fall and that’s why there are ‘digital coaches’. My empathy has been retrieved from an old backup tape. I’m sorry if my lack of understanding ever inconvenienced anyone.

The functional Pi Racket

I have a love/hate relationship with Clojure tooling.

I wanted to learn functional programming (FP) in a Lisp because:
1. There’s a thing I want to do and it felt like the right way to do it
N.B. ‘right’ is not always ‘easiest’
2. Lisp once beat me up quite badly. I’m bigger now. I wanted to go back and punch it on the nose
3. I won’t really ‘get’ immutability until I do some, with no option to cheat.
3. I find homoiconic functional programming conceptually elegant…

…then you try using the Clojure development environment and discover there isn’t one that everyone agrees on and the one used by expert requires you to learn a new language of keyboard hieroglyphs first.

I’ve done just enough Lisping to think that we are being as irresponsible teaching kids only object oriented programming as the BBC were in teaching them BASIC, but it would be actual child abuse to introduce them to FP via emacs and a language dependent on the underlying Object-Oriented Java Virtual Machine for it’s connection to libraries & reality.

This morning I realised I hadn’t plugged my Raspberry Pi in for ages. If you were a child who started coding with Scratch and a few drum loops on Sonic Pi then maybe a bit of the Squeak Smalltalk (Scratch is written in Squeak) or Python in a nice IDE, imagine being handed the ancient emacs scrolls and sent into a corner for a week to learn spells, before you could even start to learn to function. FP is going to initially make soup of your flabby imperative, ‘place is state’-damaged brain anyway. There is no need to make it harder. Teaching languages don’t have to train you for a job, only to think.

If we are going to raise functional children, we need a gentle slope up to Clojure. Clojure is probably the best practical language but it’s too hard. I’ve seen a few people suggest starting with Racket, which is a version of the Scheme Lisp dialect. This morning I poured DrRacket onto my Pi.

There was a minor hiccup with DrRacket not knowing what language I wanted it to read. Kids would need to be protected from that. I wanted “Determine language from source”, not to tell it I was a ‘beginning student’.

Because DrRacket is multi-lingual, the first line of the source code tells it what language to read:
#lang racket

You type in code then press the run button. This is not your grandfathers emacs REPL. Children should have no natural fear of their (parens). Ooh look, cats!

#lang racket

(define (extract str)
(substring str 4 8))

(extract “the cats out of the bag”)

;;-> “cats”

Relative re-energising in 2018

I read the instructions on my microwav(abl)e lunch: “800W for 4 minutes”. I wondered if that was input or output power. If microwaves got more efficient, would there be an increase in burned food? I needn’t have worried. Our microwave is 1200W in, 800W out but is that Root Mean Square, like a guitar amp? That’s how to blow up 100W speakers with 50W valve amps. They’re Peaky Bosters, like that Cillian Murphy’s accent in Series 1. Should I worry whether my risotto rice will assplode at 3:2 efficiency.

“Why would They label things relative to an obsolete technical standard?”, you might ask, if you’d never seen a modern 11W, 50W-equivalent(ish) light-bulb. You’d think ‘They’d at least have introduced a light-output based standard. There is a standard: ‘Lumens’ (total) and/or ‘Lux’ (intensity.) That’s an adventure for another day.

How many Horse-Power is your car; what size of horse; and how frisky is it feeling? I took a photo of a horse once, using an Digital Single Lens Reflex with a zoom lens that was specified by a foal length in Millimeters equivalent to a 50mm lens on a 35mm diameter camera with a slightly different frame width:height ratio. There are no sprocket holes on the digital either.

I’m trying out dropping ‘title-case’ in blog post titles. I didn’t even know what it was until a week ago. Unnecessary upper-case letters in titles appear to upset the design sensitivity of the font-folk. They have other ways of emphasising and I prefer not to offend people’s aesthetic until I mean to. I was persuaded to conform because the convention scrambles structure, content and style, while over-loading capital letters.

Writing Wrong

I’ve always admired skillful calligraphy and my handwriting isn’t awful, so I’ve thought for a few years that I’d like to try some simple lettering for an art-break from all the digital typing. I’ve bought some cheap cartridge pens with italic nibs in a range of widths. They are flat ended, so they make a broad stroke when used vertically and thin horizontally. I’ve always assumed calligraphers modified the width of the line by rotating the pen. They don’t.

I discovered that modern calligraphers use a pointed nib that splays with pressure, to vary line-width. Now, of course, I’ve realised that would be a lot easier to simulate with a pressure sensitive tablet, without all the messy ink. I can’t help it; I’m a software guy. I’m more about the tools than the medium and I like to have an undo.