Showing posts with label Computing-Science. Show all posts
Showing posts with label Computing-Science. Show all posts

2022-05-09

Trampolines - fun way to make recursion not stack overflow

(We'll use JavaScript for today, running in the Firefox developer console.)

No doubt when you learned recursion, you learned that each recursive function call uses stack space to do its work.  There's only so much stack space.  So unless your programming language has a special feature (called tail call elimination), a recursive function can eventually exhaust all stack space, leading to the famous stack overflow error (not the web site).

For example, let's write a loop to sum up numbers from 0 up to some N like this:

let sum = 0;
for (let i = 0; i < 10000; ++i) sum += i;
console.log(sum); // prints: 49995000

Now a recursive version might look like this:

const loop = function(i, sum){
  if (i < 10000){
    sum += i;
    return loop(i + 1, sum);
  } else {
    return sum;
  }
};
console.log(loop(0, 0)); // prints: 49995000

As you can see, a loop is just a recursive function call.

The above is a nice, simple demo of converting a loop to recursion.  But if instead of summing up to 10,000, we sum up to 100,000, then the loop prints 4999950000.  But the recursive function prints:

Uncaught InternalError: too much recursion

With a link to: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Too_much_recursion

Trampolines

No surprise, like the title says, trampolines can fix this!

The key is to not allow the loop function to run loop(i + 1, sum), because that'd consume stack space!  Instead, the loop function will return a function called a thunk.  That thunk function, when run, will run and return loop(i + 1, sum).  This also means a thunk can return a thunk!

The function that runs loop, and any thunk functions, is called a trampoline.  That's because the thunk function the trampoline runs may return a thunk, and if so, that thunk will get run too.  The thunks keep bouncing off of the trampoline function.  Until one day a thunk returns a value instead of a thunk!  Then the trampoline's job is done, and that value is returned.

Because the thunk itself only ever uses a single "frame" of space on the stack, rather than recursively using more and more stack space with recursive function calls, and so the stack overflow error is avoided.

Here's how the code will look:

const loop = function(i, sum){
  if (i < 100000){
    sum += i;
    let thunk = ()=>{return loop(i + 1, sum)};
    return thunk; // rather than returning loop(i + 1, sum)
  } else {
    return sum;
  }
};
 

const trampoline = function(){
  let tv = loop(0, 0);
  while (typeof tv === 'function'){
    tv = tv(); // returns either a thunk function or a value
  }
  return tv;
};
 

console.log(trampoline()); // prints: 4999950000

Trampolines running thunk-returning thunk functions is a generic technique that's applicable in other languages and situations too!


Tail Call Elimination: no need for trampolines

If your programming language has full support for an optimization called Tail Call Elimination, the above trampoline technique is completely unnecessary.

It turns out JavaScript at one point had this optimization planned.  It was to be an "invisible" opportunistic tail call optimization (TCO).  Meaning that if you correctly wrote a proper recursive function call in tail position, then TCO would kick in, and it wouldn't consume stack space (thus no stack overflow).

TCO is currently only available on Apple's Safari browser and on iOS [1].

Google's V8 team apparently came to the conclusion that TCO makes the wrong tradeoff.  Because it's an opportunistic optimization, it's very easy for a programmer to write code they think would get TCO, but actually won't, and it can be very difficult to discover the error during testing.  They advocated for an explicit syntactic way to designate a recursive function call as requiring tail call elimination.  But... well, it all fell by the wayside and was never picked back up [2].

Interestingly, the Clojure programming language's creator, Rich Hickey, basically made the same argument.  In Clojure, recursive function calls requiring TCO must be written explicitly with a recur syntax.  In that case, no trampoline is needed, and the recursive function call won't overflow the stack.

 

[1] https://kangax.github.io/compat-table/es6/

[2] https://stackoverflow.com/a/42788286

2020-12-23

Why upgrade past Java 8?

What reasons are there to use Java versions newer than Java 8 (JDK 1.8)?

I'll give two: (1) security, and (2) great new features!  Let me explain.

(1) security

The last "major release" of Java was Java 9.  The Java upgrade cadence changed at that point.  They're now on a steady stream of "feature releases" model.  Kind of like how there's no major release of Chrome, Firefox, or Windows 10 nowadays... it's just a stream of feature releases.  Java's cadence is 6 months, so about every 6 months, they ship and bump the version number.  JDK 15 was released not long ago.

So who cares?  Well only the current release (JDK15 as of this writing) gets proper maintenance and security updates for free.

Note "for free".  Certainly some software development shops will stick with old JDKs, but they might have good reasons and good mitigation for using old JDKs.  Good reasons like certain customers are stuck (for whatever reason) with old JDKs, or vendors of certain dependencies they need are stuck with old JDKs.

Good mitigations include... paying for paid Long Term Support versions of Java from a JDK vendor.  E.g. it looks like Azul offers a JDK 8 LTS, although the current LTS from any vendor is JDK 11.  The next LTS is JDK 17 scheduled for September 2021 (because of the stream of feature releases model, JDK 12 thru 16 are relatively small feature upgrades, hence the gap between the LTS versions).

You can even use the "free LTS" versions if you want to download those binaries from Oracle, Red hat, or Azul etc., just don't expect actual support without paying!  Mostly they backport security fixes from current version to the latest LTS version, and provide real support for paying JDK LTS customers.  So "free LTS" builds aren't really fully supported for free.  If you must use an LTS release, at least use the latest one (that's JDK 11).

But really, for free security and maintenance, you should just use the latest version.  It's no different from Chrome or Firefox... you should always use the latest to avoid security vulnerabilities.

As for which vendor to choose from? There's Oracle, Red hat, Azul, Amazon Corretto, AdoptOpenJDK, etc.  But they're all built from the same OpenJDK from Oracle, even Oracle's JDK, and they contribute back upstream to OpenJDK.  If you want a slick downloads page and easy installers, AdoptOpenJDK and Azul looks pretty ok.


(2) great new features

Java has a lot of great features in newer releases.  These features aren't just for looks, they bring life back into Java.  I know... "kids these days"... always wanting

  • type inference --- like in Swift, C#, etc
  • lambdas --- like in lisp, C++11, JavaScript, etc.
  • async --- like in JavaScript, rust, etc
  • better garbage collectors --- like Go

But those language features are, rightly or wrongly, table stakes to be considered an up-to-date language nowadays.  Even modern C++ has type inference and async, and smart pointers with garbage collection (reference counted).

So...

  • Java 8 has lambdas
  • Java 10 has type inference (use var)
  • I believe Java 16 will have virtual threads (Java's better answer to async) from Project Loom
  • Java 15 has better garbage collectors (by some metrics), and in fact multiple GCs to choose from for different use-cases: Shenandoah, ZGC, and G1 (admittedly, only more advanced development might care about GC performance)
  • There's multiline text blocks since Java 15, finally
  • There's extended switch expressions that can yield values since Java 14
  • and also a safer switch statement/expression using "arrow case" labels instead of "colon case" labels since Java 14
  • Java 9 introduced JShell, which is fantastic to be able to use a REPL to test out Java code

There's so much to get excited about!  There's a joke about Java being the new Cobol.  But not anymore with features that bring it parity with other languages.

2020-06-30

Stop Netbeans downloading whole 1GB maven index

Netbeans for Java programming with Maven likes to download the Maven index that's over 1 GB in size.

There's basically three ways to stop that huge download for 3 different situations:

(1) Temporarily don't want auto updates

If you already downloaded the index, the updates are smaller but still sizable.  One way to to stop it re-downloading the updates is to go to:

Tools > Options > Java > Maven > Index > Index update frequency > set to never.

Then click "Index Now" in that window only whenever you want an update.

(2) Just don't want Maven at all

If you don't have the index downloaded yet (e.g. a new install) and basically never want to use Maven, then in that same window, you could instead check off:

Completely disable indexing

As it warns you, lots of features will be disabled, but if you're not using Maven, who cares?

(3) Want Maven index without the download

This is amazing, there's this plugin you should get and it'll solve this problem: Maven Remote Search plugin.

It's old and it says it's for Netbeans 8.2 (the super old Oracle version), but I tried it out and it works for the new Apache Netbeans 11 and 12!

It lets you search the Maven index online rather than downloading the whole index to your local disk (which is crazy).

The github repo for the plugin is active recently with a historical build, so hopefully it'll get its version bumped and put on the Apache Netbeans plugins web page (which I don't think exists yet...).


Bibliography:

2020-03-25

One way to use SemVer for software versioning

Everyone has their own system for versioning in their software development process.

Semantic Versioning is very popular of course.  It basically takes the form of:

major.minor.patch-prerelease+build
  • Major for breaking changes.
  • Minor for backwards compatible feature additions.
  • Patch for bugfixes meant to be backwards compatible.
  • Pre-release tags for internal versioning, building up to a release.
  • Build for internal build numbers, useful if you build a lot.
There is a precedence order to SemVer numbers to essentially designate which version is "newer" in some sense.

Pre-release and Build tags do not participate in the precedence order.   So when specifying ranges of versions, those pre-release tags are kind of ignored in things like NPM contrary to precedence order as SemVer defines it --- reality is different than theory, right?

Pre-release tags are great for Designating development stages but when they are removed to do a non-pre-release release (e.g. a final release), it messes up the lexicographical ordering --- i.e. messes up the order in which they show up in my file browser. haha.

How I use SemVer

So I'm trying a SemVer compatible system that respects the 2nd and 3rd laws: "Don’t mess with math", and "Make friends with infinity.  In other words, don’t be afraid to increment".

The basic idea is: keep pre-releases to a patch level, release at the next patch level.

The rules are:
  1. Start at 0.1.0.
  2. Increment patch number to make a release
  3. Increment major, minor, or patch (whichever you're targeting for next) to make pre-releases
  4. Pre-releases are tagged a1, a2, ..., b1, b2, ..., rc1, rc2, etc.
  5. Use increasing build numbers if you need
  6. Use a "." then another build field if you must, like for adding a non-increasing alphanumeric build field (e.g. a SHA)

Example

So you'll get versions of WildApp like these, e.g.:
  • WildApp 0.1.0-a1
  • WildApp 0.1.0-a2
  • WildApp 0.1.0-b1
  • WildApp 0.1.0-b2
  • WildApp 0.1.0-b3
  • WildApp 0.1.0-rc1
  • WildApp 0.1.0-rc2
  • WildApp 0.1.1
  • WildApp 1.0.0-a1
  • WildApp 1.0.0-a2
  • WildApp 1.0.0-b1
  • WildApp 1.0.0-b2
  • WildApp 1.0.0-b3
  • WildApp 1.0.0-rc1
  • WildApp 1.0.0-rc2
  • WildApp 1.0.1
I'm going to give it a try at least.

2019-10-18

Why are these 3 open source licenses best?

I've already said that these 3 licenses are best for open source nowadays for me:
  1. Apache License 2.0 --- Apache-2.0 @ SPDX, ChooseALicense
  2. Mozilla Public License 2.0 --- MPL-2.0 @ SPDX, ChooseALicense
  3. GNU General Public License 3.0 or later --- GPL @ SPDX, ChooseALicense
But WHY??

The open source community has basically settled on 4 styles of sharing, and with it 4 genres of open source licenses.  The list above is my pick of what I think is best in each of the first 3 genres.  Let's talk about each one in turn:

1. Software developers are free to do whatever they want with my code in building their software.

These licenses are about the freedom of the developers of the software.

Look for MIT, BSD, Apache licenses, etc.

But I think Apache License 2.0 is the best because

2. Users are free to do whatever they want with my code and any modifications to my code in the software they received, even if they can't with the software's other proprietary code.

These licenses are all about the freedom of the end users who have the software, in a piecemeal fashion.

Look for MPL, EPL, LGPL licenses, etc.

But I think MPL 2.0 is best because
  • compared to MPL and EPL, the LGPL basically makes the distinction that static linking of code equals modifications to that code, but dynamic linking is not.  That just seems like a needless distinction for a license to make, and MPL and EPL doesn't make that distinction.  And I like static linking.
  • EPL 2.0 is basically a very new update to EPL 1.0 that makes the EPL even more complicated than it already was.  The main purpose was to (1) change the boundary of what counts as "my code" from a module based distinction to a file based distinction, which is what the community has standardized on, (2) make it more internationally usable, and (3) add in GPL compatibility as an opt-in.

    Unfortunately, GPL compatibility is opt-in and not default making it even more complicated when mixing EPL 2.0 with/without GPL secondary license, and EPL 1.0 code which was never GPL compatible.

    So if your community has settled on EPL (like many in Java or Clojure), then maybe sticking with what the community is using is easiest.  Otherwise, it's hard to make an informed use of the EPL as an individual, unless you've got lawyers on retainer... which is maybe why the EPL is very well regarded by businesses?
  • It is compatible with Apache 2.0.
MPL 2.0 on the other hand has GPL compatibility by default, unless opted-out of.  It's much older so it's better known and understood, still very well regarded, and used by large projects like Mozilla for Firefox, Adobe for Flex, LibreOffice, etc.  And it's relatively short and easy to understand, so MPL 2.0 it is! 


3. Users are free to do whatever they want with all of the code in the software they got from the software developers.

These licenses are all about the freedom of the end users who have the software, not about the developers'.

Look for GPL.

This is the classic "viral copyleft" thing, although talking about strong/viral copyleft is kind of more confusing than helpful (see Weak or Strong is Wrong) because, philosophical discussions aside, it's really just about what kind of code sharing you want to take place with your code you authored.

Having said that, if you incorporate MPL 2.0 or Apache 2.0 code into a GPL code base, the whole code base has to be distributed as GPL moving forward.


4. Users are free to do whatever they want with all of the code in the software they use from the software developers.

These licenses are all about the freedom of the end users using the software over a network.

Look for AGPL, SSPL, etc.

GPL had a SaaS loophole / ASP loophole:  what happens if the end users never got the software, because they only used it running in the "cloud" (i.e. on computers they don't own)?

AGPL is supposed to close that loophole so that if an organization modifies AGPL software, any end user using that AGPL software in the cloud must be able to do anything they want with its' code.

More recently, AGPL was found to have a no-modification loophole: what happens if an organization just uses and doesn't modify AGPL software?  The AGPL doesn't compel code sharing in that case!

So companies could containerize AGPL software, build an API around it to use it internally, etc., and as long as they never modify the actual AGPL software, then they could use without ever sharing any code.

Some patched that loophole with the Commons Clause.  MongoDB took a different path by creating the SSPL.

I don't know enough about this genre of sharing to suggest any license as best.  Reading SSPL Was Not Commons Clause, it's clear this is still cutting edge licensing legal stuff.  If you're looking for a license for this genre of sharing for any serious work, you'd probably have your own lawyers anyway.

And I'm definitely not a lawyer, so let's just agree to take this as entertainment.  :)

2019-10-12

These 3 licenses are best for Open Source


Choosing an open source license is confusing.  There's so many!  But I've narrowed it down to the 3 best ones for me nowadays.

I'm not a lawyer, so take this as entertainment.  :)
  1. Apache License 2.0 --- Apache-2.0 @ SPDX, ChooseALicense
  2. Mozilla Public License 2.0 --- MPL-2.0 @ SPDX, ChooseALicense
  3. GNU General Public License 3.0 or later --- GPL @ SPDX, ChooseALicense
Which you use depends on what kind of sharing you want to do.

Use Apache 2.0 license if:
    1. you want anyone to be able to use your code however they want, 
    2. including building bigger projects based on your code with the bigger work licensed however they want (including possibly "all rights reserved" proprietary licensing), 
    3. without expecting them to share anything back in return,
    4. without expecting them to acknowledge they used your code,
    5. and without expecting them to share your code that they used.
Use MPL 2.0 if:
    1. you want anyone to be able to use your code however they want,
    2. including building bigger projects based on your code with the bigger work licensed however they want (including possibly "all rights reserved" proprietary licensing),
    3. but you expect that any changes they make to your files are shared back in return,
    4. you expect that they will acknowledge they used your code,
    5. and you expect they'll make available your code that they used.
Another great thing about MPL 2.0 and Apache 2.0 is that they are compatible with each other!
Use GPL if:
    1. you want anyone to be able to use your code,
    2. including building bigger projects based on your code but with the bigger work also GPL licensed,
    3. and any changes they make to your code, as well as any code added to your code even if in other files or modules, are all shared back in return,
    4. you expect that they'll acknowledge they used your code,
    5. and you expect they'll make available your code they used, and also any code they add, even if they added them in other files or modules.
Notice the big distinguishing point is in how much you want users of your code to share back changes or additions.  From zero sharing required (Apache 2), to sharing changes or additions to your files (MPL 2), to sharing all changes or additions whether they be in your files or in other files linked (dynamically or statically) to your files (GPL).

If you want help navigating to which license to use, this License Selector I found the best (except it's missing EPL-2.0).  While the Choose a License site from GitHub has the slickest UI, they make some questionable suggestions from my point of view, like highly suggesting the MIT (a.k.a Expat*) License instead of the Apache license.

One reasonable advice from ChooseALicense though is to choose the license common in the community you want to share in, but that's really only true if there is an equivalent license to what you'd otherwise want to use.

For example, if you want to use the MPL-2.0, but you're wanting to share in the Clojure community, then you're probably better off using the EPL-2.0 (Eclipse Public License) instead, despite the EPL 2 being very likely not as "good" as the MPL 2 by some metrics.  But EPL is only even an option as it's basically equivalent to the MPL as far as I could tell.

If for some reason you really wanted to GPL license your Clojure code, then EPL isn't going to cut it anyway because they're not at all equivalent.
    * this is different from the MIT / X Consortium License.

    2019-07-23

    Create React Native App using TypeScript compiled with Babel


    Here's every step to creating a React Native app, written in and type checked with TypeScript, but compiled with Babel 7.

    You're assumed to have some proficiency with using the terminal.

    Tools to Install on your PC

    I'm on a Mac, but the steps shouldn't be much different on Ubuntu Linux or Windows.
    1. Install Homebrew.
      It's a package manager for Macs, and Linux too, but if you're on Ubuntu or Debian, I suggest just use the built-in one like APT.
    2. Install Node thru brew.
      Installing Node should include the NPM package manager with it, which is needed below.
    3. Some say to next install Yarn thru brew.
      Yarn is yet another node package manager... you can skip this if you want, it's not strictly needed, and I won't use Yarn in this tutorial.
    4. Fix NPM if you installed Yarn.
      I actually mentioned Yarn at all only because with Homebrew, you might now need to fix the Node NPM install as it might be broken by installing yarn.  Simply[1] run: yarn global add npm.  Remember, we don't need Yarn in this tutorial though.
    5. Install React Native CLI thru npm:$ npm install -g react-native-cli
      This is basically a template that creates a RN project for you to start from.
    [1] https://stackoverflow.com/questions/33870520/npm-install-cannot-find-module-semver/49422151#49422151

    New Project with React Native

    1. Create a React Native project:
    $ react-native init CoolProject

    1.5. Upgrade core-js:
    I got an error like this:
    warning react-native > create-react-class > fbjs > core-js@1.2.7: core-js@<2.6.8 is no longer maintained. Please, upgrade to core-js@3 or at least to actual version of core-js@2.

    You just need to upgrade core-js.  Go into your CoolProject folder and run:
    npm install --save core-js@^3

    2. cd CoolProject to go into the new project's root directory, then install Babel:
    $ npm install --save-dev @babel/core @babel/cli
    I assume this will install for you Babel 7 or above.  We'll need it later to migrate to TypeScript.

    3. Create a lib folder in the project root.
    $ mkdir lib
    The lib folder will be used to contain the App's JavaScript files. Traditionally, the folder would be called "src", but looking forward, these JavaScript files eventually will be produced by the TypeScript compiler for us.

    So instead, we're going to reserve "src" for later when we migrate to TypeScript, instead of calling it "src" right now when we're still dealing with just JavaScript JS, or JSX, files.

    Separating the TypeScript and the compiled JavaScript files is a technique to avoid in-source builds (a usual technique used in compiled languages like C++: see e.g. in-source vs out-of-source builds).

    2019-03-25

    Book Review: The JavaScript Handbook by Flavio Copes

    If you're a competent programmer but have been away from JavaScript for some time and want an extremely brief overview of the updates to JavaScript, in bite size form, then this book (The JavaScript Handbook) is for you.

    Flavio goes over all the new features in JavaScript from ES6 to ES2018. Listing out each feature or change and giving an extremely brief description of it.

    This book reads like a collection of very short blog posts though. And would benefit from more editing, both on a sentence level and on an overall topic cohesiveness level. That's a small nitpick in what is overwise a good set of writing.

    There's definitely two major parts to the book. First part is extremely brief in describing the changes in each version of ECMAscript.

    Second part basically goes over all the changes, again, but this time in more detail. Not a lot more, but sufficient for a competent programmer to know enough.

    E.g. if you don't know that much about async and promises on a conceptual level, this book isn't going to teach you enough to really use those features productively.

    Or if you don't really know the problems with the "this" keyword in JavaScript, the book's description of it in relation to how it works and how it's changed with arrow functions isn't the most enlightening. Some sentences on it, superficially without a deeper understanding of how programming languages work, are downright contradictory sounding.

    All in all though, I went through it cover to cover, and the book does a good job for reviewing changes to JavaScript for the competent programmer.

    For next to free (i.e. email signup), it's hard to beat.

    2019-03-20

    How to migrate ReactXP App to make an Electron Desktop App

    ReactXP comes with a few sample apps. The TodoList app is the most developed and closest to the structure of a production app written in TypeScript, but doesn't target Electron.  Here's how to migrate it to run on Electron so it could work as a desktop app.

    I'm on a Mac, but Electron is cross platform with Windows and Linux so it should work there too.  ReactXP 1.6.x is current right now (hilariously, it upgraded from 1.5.x just as I was working on this and it introduced some new error so this migration is totally in beta).

    Strategically, the idea is ReactXP can already directly target the web via React (in addition to native iOS, Android, and Windows via React Native).  So we just target the web with ReactXP, modify the web page loader to run in Electron, and modify some code so it doesn't assume it's running at the root of a web server.

    Make TodoList into a web app. Run it on a local dev web server

    First, use git to clone the ReactXP repository:

    git clone https://github.com/microsoft/reactxp

    In the reactxp/samples directory, you'll find the TodoList app. Open it:

    cd reactxp/samples/TodoList/

    Install Electron into it:

    npm install --save-dev electron

    Now we need a web page to load the app into Electron.  We'll use the default one from Electron quick start.  Just copy the main.js from electron-quick-start into the TodoList folder, and rename it to electron-main.js just for clarity.

    2019-03-09

    Maximally Cross Platform with React?

    Once upon a time, going cross platform meant making an application that ran on both Macs and Windows, and maybe Linux/Unix if you're into that crowd.

    Now everything is fragmented and compartmentalized.  Consider what "platforms" there are now for making apps:

    1. desktop web browsers --- i.e. Chrome, Firefox, Safari, vs Edge --- further divided by Macs, Windows, and Linux (at least for browsers that are cross platform, ha!)
       
    2. mobile web browsers --- i.e. iOS vs Android --- further divided by phone vs tablet display sizes
       
    3. Electron desktop apps --- i.e. Macs, Windows, vs Linux (built with web browser technology)
       
    4. native desktop apps --- i.e. Macs, Windows, vs Linux
       
    5. native mobile apps --- i.e. iOS vs Android --- further divided by phone vs tablet display sizes
    Some of the above differences are a matter of building user interfaces sized for use on that display size, while other differences are a matter of framework (e.g. Cocoa vs Android SDK).

    But at worse, that's still 26 different platforms to build for!  There are technologies that help bridge the divide, and one family of such tech is called React.

    Here's a survey of some React based technologies and which platforms they work well for.


    2019-03-06

    Create React Native App using TypeScript with Babel and Expo

    (updated 2019-07-23 for clarity)

    Here's every step to creating a React Native app (with or without Expo), written in and type checked with TypeScript, but compiled with Babel 7.

    You're assumed to have some proficiency with using the terminal.

    Tools to Install on your PC

    I'm on a Mac, but the steps shouldn't be much different on Ubuntu Linux or Windows.
    1. Install Homebrew.
      It's a package manager for Macs, and Linux too, but if you're on Ubuntu or Debian, I suggest just use the built-in one like APT.
    2. Install Node thru brew.
      Installing Node should include the NPM package manager with it, which is needed below.
    3. Some say to next install Yarn thru brew.
      Yarn is yet another node package manager... you can skip this if you want, it's not strictly needed, and I won't use Yarn in this tutorial.
    4. Fix NPM if you installed Yarn.
      I actually mentioned Yarn at all only because with Homebrew, you might now need to fix the Node NPM install as it might be broken by installing yarn.  Simply[1] run: yarn global add npm.  Remember, we don't need Yarn in this tutorial though.
    5. Install Expo thru npm:$ npm install -g expo-cli

      Expo is apparently kind of a mini-platform for running React Native apps, and makes it easy to test a React Native app on devices through its Expo app, or on Macs and PCs without resorting to an Android or iOS emulator (which is great, because those emulators are dreadfully slow in my experience).  Plus installing Expo should include React Native with it.
    6. Install React Native CLI thru npm:$ npm install -g react-native-cli
      This is basically a template that creates a RN project for you to start from.
    [1] https://stackoverflow.com/questions/33870520/npm-install-cannot-find-module-semver/49422151#49422151

    New Project with React Native or Expo

    1. Create a React Native project (possibly thru Expo):
    $ expo init CoolProject
    or alternatively without Expo:
    $ react-native init CoolProject

    1.5. Upgrade core-js:
    I got an error like this:
    warning react-native > create-react-class > fbjs > core-js@1.2.7: core-js@<2.6.8 is no longer maintained. Please, upgrade to core-js@3 or at least to actual version of core-js@2.

    You just need to upgrade core-js.  Go into your CoolProject folder and run:
    npm install --save core-js@^3

    2. cd CoolProject to go into the new project's root directory, then install Babel:
    $ npm install --save-dev @babel/core @babel/cli
    I assume this will install for you Babel 7 or above.  We'll need it later to migrate to TypeScript.

    3. Create a lib folder in the project root.
    $ mkdir lib
    The lib folder will be used to contain the App's JavaScript files. Traditionally, the folder would be called "src", but looking forward, these JavaScript files eventually will be produced by the TypeScript compiler for us.

    So instead, we're going to reserve "src" for later when we migrate to TypeScript, instead of calling it "src" right now when we're still dealing with just JavaScript JS, or JSX, files.

    Separating the TypeScript and the compiled JavaScript files is a technique to avoid in-source builds (a usual technique used in compiled languages like C++: see e.g. in-source vs out-of-source builds).

    2017-04-02

    Which programming language to teach? A principled choice

    Java is still one of the most popular programming language to teach the young or newbies to programming.  It's a very problematic choice.  See:

    1. The problem of Object Oriented Programming is an education one
    2. Learn Python instead of Java as your first language [1]
    3. Java has deep expression problem for beginning students
    4. Governments mandating which programming language to teach
    Having looked at some of the problems and issues before, I want to be constructive and offer some principles for how to choose which programming language to teach instead.


    1. Principle of no magical incantations

    This can be viewed as a language feature vs. library supplied functionality issue.  The latter is mostly okay, but the former should have no magical incantations that students need to learn.

    Magical incantations are language features like the "static" keyword in Java.  You could imagine a student asking:
    What does "static" mean in the "main" method declaration?  Why is it "static" and not something else?  What does "static" do?  Why do I need to write "static" when I don't know what it means to make something "static" vs not static?  I don't want it "static", I want it "grounded", can I write that instead?
    Now you could imagine a teacher answering:
    The answer to why, what, how, etc., would require explaining OOP and how it's implemented in Java and...  Look, just write 'static'.  It's just the way it is.  Just do it this way or else it doesn't work.  It's a magical incantation the Java gods require you to recite.
    The more language features required to write even a simple program, the more things students have to learn or be ignorant of but use (i.e. magical incantations).

    That makes it more likely that students have to learn everything about the programming language all at once just to do even the simplest thing at all.

    2. Minimize concepts required to start doing stuff

    The more that foundational programming concepts are required, the more programming language specific things students must think about whilst at the same time thinking about solving the actual (i.e. non-programming-language, "business") problem in its problem domain.

    Otherwise, it'd be like students have to learn everything in the programming language all at once in order to do anything at all.

    3. Idiomatic code from the start

    A programming language that encourages writing idiomatic code from the very start reduces either the magical incantations required in writing idiomatic code, and reduces dumb code written stupidly just to avoid learning the magical incantations.

    Otherwise, students have to learn everything all at once just to do anything at all.

    Magical incantations are not hidden machinery!

    I'm not advocating learning C because it doesn't have the magic of a garbage collector (GC)!  The GC is not a magical incantation: it's mostly hidden machinery.

    Hidden machinery works quietly, never broadcasting its own existence, and isn't in your face about what it does.  It doesn't offer an affordance where none is called for, or where it would be inappropriate for the target user.

    Magical incantations are flamboyant and in your face.  You know it's doing work because the magician is showing you that work is being done through the incantations, even if what's shown and what's done might very well be disconnected from each other.

    To a newbie, the "static" Java keyword (to pick on something as an example) is magical incantation.  The Java GC is hidden machinery that we should be thankful for having every day.

    Hidden machinery that makes a language easier for a newbie to learn is great.  Magical incantations that calls out its own existence is not helpful.

    Magical incantations are also not Spooky Action at a Distance.  But that's a topic for another day.


    Afterword
    I wrote the above years ago (around 2013 February 4), and only now slightly expanded and lightly edited it to share here.

    [1] I don't recommend learning Python as your first language anymore for various reasons (but I'd certainly recommend learning Python over Java as your first language!).

    2016-12-03

    Elixir and Phoenix on MacOS for the First Time: install to first project

    Let's install Elixir and Phoenix on MacOS, and create our first web app project.

    I looked through 3 separate web pages to figure it out (it was relatively easy), and thought it'd help to gather it into a single page of 10 steps.

    What's Elixir?  Elixir is a programming language that superficially looks a little like Ruby, but more importantly is designed to be dynamic, functional, and capable of building concurrent, distributed, low-latency and fault-tolerant systems (perfect for the web!).

    It does that by running on the Erlang VM (like a Java VM, not like a VirtualBox VM), and that also gives developers access to Erlang’s ecosystem (this reminds me of how Clojure runs on the JVM, providing access to Java's ecosystem).

    What's Phoenix?   Phoenix is an Elixir framework implementing the server side of a web framework for modern web applications.  Like Ruby on Rails or Python's Django, but Phoenix is written in Elixir and derives benefits from that (in addition to whatever other advantages it may have as a framework - we're not comparing frameworks today).


    (1) Install Homebrew

    To begin, you need Homebrew installed on your MacOS.  Homebrew is a package management system that makes installing lots of developer software much easier on Macs.

    Once installed, especially if it's been a while since you've last used Homebrew, make sure to update it (commands after "$" are to be typed in your terminal window):

    $ brew update

    Do a self diagnostic to make sure it's all okay, carefully read the instructions it provides:

    $ brew doctor


    (2) Install Elixir

    Elixir requires Erlang to be installed.  Fortunately, the Homebrew package will automatically make sure of that.

    2016-11-19

    Clojure Programming Cookbook - a Book Review

    It's been a while since I've looked into programming Clojure again, having been preoccupied with C++ lately.  With the new Clojure Programming Cookbook, I've gotten to see a number of new developments in the Clojure ecosystem that is quite exciting.


    The book is very example oriented, basically being a collection of code recipes for accomplishing common programming tasks with Clojure.  I like how it starts from very basic interactive programming and macro usage (this is a Lisp after all), all the way to talking about concurrency, parallel processing, and cloud-based tasks.  Each recipe is accompanied by brief explanations, preambles, and some cross references to related recipes in the book.

    Each recipe is basically self-contained, so I wouldn't necessarily recommend reading the book like a book, but instead to use it as a "random access" set of references.  The ebook version is probably best in terms of allowing for full-text searching for key terms, and for clicking on relevant topics in the table of contents to look up useful recipes.  I'd personally prefer having the PDF ebook, but that's just me.

    As a reference book, it's great if you already have familiarity with Clojure, but this book is probably okay for those of you programmers who don't yet know Clojure and want to learn it.  I'm not sure it's that great if you just don't know how to program and want to learn programming starting from nothing.  On the other hand, I could imagine a course instructor might be able to bootstrap the book with additional content to help absolute beginners get started, then point out recipes in the book to try out from time to time.

    What's neat about this book for me is that as I've been away from Clojure for a few years, looking at this book I see recipes for topics I'd like to try out.  Topics I've heard of but just haven't followed along with over the years.  Like Transducers, and Om.Next.  So it's nice to see some self-contained examples of these exciting new developments in the Clojure ecosystem.  But given that it is just a cookbook, it doesn't seem to get deep enough into any specific particular topic for me to feel like I really know what's going on.  For that, I'd need to look to additional resources.

    So there's definitely some caveats, but it is a pretty decent and easy going kind of book.  For a lower intermediate Clojure programmer, it's definitely a good resource to look into, maybe to help get you from programming on a single machine to programming for the cloud (AWS, etc.).  For upper intermediate programmers who's been away from Clojure for a while and want to see some new Clojure developments, I'd definitely see about getting it if you chance upon a sale.  The book lives up to its name as a cookbook.

    2016-09-06

    Different Types of Learning Tasks and Content Delivery Styles

    The following lists a number of learning tasks students may engage in by teacher instruction, and thus they are instruments of teaching a teacher may employ.  Notes regarding each are provided briefly to highlight a range of possible tools teachers may use to engage students in learning.  These are arranged generally speaking from easiest to most difficult to employ effectively.

    Every single one of these types of tasks and styles has its rightful place in a course --- there is no magic bullet solution.  Exclusive use of any single style or type of task is not necessarily a good thing as there are always trade-offs to be made.  This list is not meant to be a complete or exhaustive listing of all possible learning tasks or their categorization or description, but a way of thinking about them to help create an effective mixture of learning tasks for any course of learning.

    Lectures
    - teacher-oriented learning task
    - active instrument
    - students may remain largely passive for task completion, and can passively wait it out

    Theory and verbal/textual explanations are delivered by an instructor to students (focuses on "telling" over "showing").  The delivery is often best done scripted and in an organized manner, almost like a audio/visual version of a printed book delivery of theory or textual explanations.  This term describes a type of teacher-oriented activity.

    2016-09-01

    New angle on math education: lessons from product design

    Or a user interface for learning math

    High school is when many students typically first encounter some of the greatest difficulties in learning what forms the basis for learning post-secondary level math. Those are, therefore, some very critical years in a student's math educational career. If it is important to get more students to consider entering a STEM career (and I'd argue it is [1]), then it is important to consider how math can be taught to these students so they'd be more interested in it, and be better at it later on.

    The following is a long piece discussing the problems facing designing a better math educational experience, complete with the principles of design that can be used to solve such problems, closing with some guidelines for how to create a better course.  In principle, all of the following can apply equally well to other subjects, like computing science, or English, but math education is tough, so I’m picking on the hardest as an example.

    Math course as a product

    Just how do students experience of learning math get formed? Rather than looking at it in a traditional teacher's mindset, let's look at it in terms of a commercial product designer's mindset. That means we see students as interacting with a complete, full-fledged math education product that promises students that they'd get what they want.

    2016-08-16

    Complex numbers, exponentials, and the 2D plane: geometric and physical intuitions leading to Euler's Formula


    **And why polar coordinates turns out to be really useful, and not just for tracking down polar bears.**
    
    Today's goal is to re-imagine the two-dimensional plane, 
    to develop a better understanding of how the 2D plane
    relates to complex numbers and the complex exponential functions.
    
    We'll do so using mainly our physical and geometric intuitions,
    with some basic high school math as our only support.
    
    So we'll need nothing more than high school algebra: i.e.
    rules of exponents (i.e. Sum of Exponents rule),
    rules of logs (i.e. Sum of Logs rule),
    knowing how to use the exponential and 
    logarithmic functions with real numbers,
    knowing basic trigonometry around the unit circle,
    and maybe a little about how angles are measured in radians.
    
    There's no need to know anything about complex 
    numbers or vector math.  In fact, we don't even need to know anything about
    quadratic equations and how calculating its roots can give us imaginary numbers.
    
    Best of all, by the end, **we're going to re-discover Euler's Formula and 
    Euler's identity using only our physical and geometric intuitions** --- no power 
    series, and no calculus.
    
    Let's start!
    
    ## Grid View: Coordinates
    
    The usual way to think of the 2D plane so that we can give every point
    on the plane an "address" is to draw the x- and y-axis, then draw grid
    lines everywhere.  This is the **grid system** that we'll start with.
    
    ![Standard cartesian plane grid system with x and y axis](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh3g6uNYM5hpFLcYf9hG9cZ1RNN6q6UQIKGA902iGtaubcEKKTEUEczU1T5Z3kPGdsLX9FgUELGUfFGykdOQUCuUUimSQlKVLE43c6cRFUpV5sRQ1nv7EZ1yuzzsWHiltBTBuLH2ZCOpEw/s1600/1_grid.txt.png)
    
    Then every point can be addressed by a rectangular coordinate
    \\((x,y)\\) as usual.  If all we know is standard grade-school math,
    then we can't really do much with these coordinates.  That means there's no
    arithmetic of coordinates in standard grade-school, i.e. so we can't
    add or subtract coordinates from each other.
    
    Rectangular coordinates are perfectly fine for giving each point on the
    2D plane an address though.
    
    ![Standard cartesian plane grid system gives every point an x and y coordinate component](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhvSPWV2REoaUOoB5zK9EClhwaShc8Anbm8j3FUq3vZeJFn_potwDTCMMtKjPWcQTW_L_9Ri9HJWMLaOpmttaYcNGHU631KcmwHTZZryxuQ-VaSXgkndyqtmBti-NYKC2ExlKM2NMVhiZM/s1600/2_xy_pt.png)
    
    
    ## Rectangular View: Right and Up
    
    We can **create** a kind of arithmetics of coordinates though
    if we adopt a geometric view of the 2D plane rectangularly:
    
    - Define the **rt** unit of measure as the ruler pointing 
      rightward of length 1.
    
    - Define the **up** unit of measure as the ruler pointing
      upward of length 1.
    
    ![Define rt and up as units of rectangular view measures in the grid](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiqGvFpuFwB8Ap6eO04TWrvhOk2tPAbGRzqbtj23F8HUoNp1CYhZpBEMwhwFQk55G1xvEcbV-iAMmsCf3CHsgzg8-oKQV45xa0TjnijV5pXe-bGMvnZKgTGrwmO6cgrBhrId1bKxxtg4fg/s1600/3_new-units-rt-up.png)
    
    Then every point can be addressed by starting at the
    origin \\((0,0)\\), and going a certain multiple of **rt**
    plus going a certain multiple of **up**.  I.e.:
    
    $$(x,y) = x \cdot\mathrm{rt} + y \cdot\mathrm{up}$$
    
    ![Example of adding 3 rt and 2 up to get coordinate at x equals 3 and y equals 2](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjJpf-so6MDiBcEMbb5sTp_elqlDucZ7TEqgNRWcNALvqMYJRMb_hFzkCxleioEj1jUWQX81nnu0DPmxU-257Ix5_TSemi7_l0q0HweAVFjO7QYWmVTtGsZLxkJcfxkCqco6iLGTEJPCNQ/s1600/4_example_rt_up_addition.png)
    
    That is an abuse of the "+" symbol to mean "go one direction,
    plus go another direction", but that's what we're trying to
    do: make arithmetic sense out of things that doesn't 
    naturally have arithmetic meaning.
    
    Notice though that the same point in the same spot of the 2D plane
    now has two ways of being addressed!  The grid view gave us **coordinates**, vs.
    the rectangular view that gave us an arithmetic **sum** of the **rt** and **up**
    units.  We now know the two different addresses are "equal" only because they
    are addressing one and the same point in the 2D plane!
    
    We haven't, however, defined a multiplication symbol for mixing
    the two units **rt** and **up** together yet,
    because what could it possibly mean to multiple a **right**
    with an **up** direction?
    

    2016-07-11

    JavaScript OOP inheritance explained with diagrams


    We're not talking about ES6 classes today.  Just ES5 JavaScript object-oriented programming.
    
    ## Prototypal inheritance
    
    People say there's at least these **3 big features of OOP** that distinguishes OOP from other styles of programming:
    
    1. Encapsulation
    2. Polymorphism
    3. Inheritance
    
    We're going to focus on the last item today.
    
    OOP in JavaScript isn't intrinsically class-based in the style of Java.  I assume you already know a thing or two about OOP in terms of Java or Python, or similar though.
    
    Instead, **JavaScript OOP is prototype based**.
    
    That means you'd just make an object `c` as you like it, no class definition required --- but if you must think in classes, imagine making a class `C` and using it to create exactly the one object `c`.
    
    Then when you want another object `s` to inherit from object `c`, you'd just do it, *no class required* --- again if you must, imagine making a class `S` that inherits from `C`, and using `S` to create exactly the one object `s`.
    
    Conceptually, it's simple, but trying to use it productively, with constructors and everything else, and it can get confusing.
    
    Rather than learning how to do class-based OOP in JavaScript (for that, see MDN's [Introduction to Object-Oriented JavaScript](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript) instead), let's try to really understand what JavaScript is doing --- from the bottom up.
    
    ## Diving in, bottom up
    
    In JavaScript, everything are objects, even functions.
    
    OK, some things are primitives... forget that, let's just see some code.
    
    By the way, I'm running all the code in the Firefox Console.  Explanations and diagrams are interwoven into the code as comments.
    
    ## Cosmic Super Object
    Let's start with the "cosmic super" object that all objects
    usually inherit from, namely the object stored at 
    `Object.prototype`.
    
    ```JavaScript
    typeof(Object.prototype); // is an object
    
    Object.prototype.prototype === undefined; // true
    Object.prototype.__proto__ === null; // true
    ```
    
    So `Object.prototype` doesn't have a `prototype`, and it doesn't
    "`__proto__`-inherit" from anything.  The buck stops here.
    
    In JavaScript, each object `o` has a `__proto__` property that
    points to the object that `o` **prototypely-inherits** from
    (as opposed to "inherit" in the class-based sense).
    
    So from here on, if `s.__proto__ === k` then we say `s` **proto-inherits** from `k`.  I use the term "proto-inherit" to distinguish from the Java-style, class-based, concept of inheritance.
    
    Yes, `__proto__` is deprecated, but it works (for now) and is easier to think with.
    
    
    We're going to start diagram out the relationship
    between the various objects we're exploring in JavaScript.
    
    ![Object.prototype UML-like diagram](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjJZIMM9zCjENTA9a-3J3tm3NwQV-KrRXFQzB5zyxwDC7Q7qPSXXrXncOHmTktqCMqdcAsw6xRAMbrKfj2FGI56gDbAwoBmqe6-ovF_ZS1tprzxwaSeHfUnqfBQ7sOSXRXbrHCA89AGQFA/s1600/d1.txt.png)
    
    As described before, if you must think in classes, then making an object
    in JavaScript is like writing a class and instantiating exactly one object
    from it, so we'll draw objects in the style of UML classes.
    
    i.e.
    
    ![UML-like class diagram example schema](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjjEss9UraMrJC7cwso34SN0A_SnETwAmxgnmLoYHQLanN68PI-Sd5Xr6KBPA1q-1HFp8H9dbkBgAUI7o6Expfhn5y4ePFGneu1sRJCoYwih4dP_NuyNeiGvysk2FqMc4lUszCaotE7dj4/s1600/d2.txt.png)
    
    
    ## Object function
    But if `Object.prototype` is an object, what is `Object`?
    
    ```JavaScript
    typeof(Object); // is a function.
    ```
    
    Huh, but it had a `prototype` property before...
    I guess functions are like objects and can have properties.
    
    In fact, there is a circular relationship between
    `Object` and `Object.prototype`:
    
    ```JavaScript
    Object.prototype.constructor === Object; // true
    ```
    
    Since functions can have properties, we'll draw them like objects
    but tag them with "fn:"
    
    ![Circular relationship between fn Object and Object.prototype](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgw2LI308pvxETX61mR7VYvqZH3mFJS71sn_ZLgoFPTygfm_jwi_LmzPXh-plk-1ZZVtPY18SIehfFFvLPtNoxFi2Ikfpuz6pET94i_1whyphenhyphenkjGLicaJFCLPw_YtxGg-BRImBw1aHKxdUak/s1600/d3.txt.png)
    
    There's a general circular relationship between functions and prototype
    objects as we'll soon see.
    
    
    ## Function function
    Since `Object` is a function, what is `Function`?
    
    ```JavaScript
    typeof(Function); // is also a function
    ```
    
    Actually, `Function` is very much like `Object` with a
    circular relationship:
    
    ```JavaScript
    Function.prototype.constructor === Function; // true
    ```
    
    But what is `Function.prototype`?
    
    ```JavaScript
    typeof(Function.prototype); // is a function
    ```
    
    So there's a general circular relationship between functions and prototype objects as well:
    
    ![Circular relationship between fn Function and Function.prototype](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiuPF29bpW2vp-gRCzPr42gT1c4CLaGu6uJCdv_FjqK6nbOUC2JqeVCeU7pxNOiUr8NnFBNGtNuJ8C8yHXvM3JnvzIC8hHsPjjU1M77zAjvML5AehBC0IQnsq_tNkpwrf8yAo445j8rOgQ/s1600/d4.txt.png)
    
    
    ## How do Function and Object relate?
    Well we already know `Object` and `Function` are both functions.
    Now observe where they proto-inherit from:
    
    ```JavaScript
    Object.__proto__ === Function.prototype; // true
    Function.__proto__ === Function.prototype; // true
    ```
    
    Wasn't `Function.prototype` a function as well? Yes and no...
    
    ```JavaScript
    typeof(Function.prototype); // recall that's a function
    Function.prototype.__proto__ === Object.prototype; // true
    ```
    
    ![Circular relationship between fn Object and Object.prototype, and between fn Function and Function.prototype](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiJhd17gDojdt-labL0wFRS4dTscyh6miYnTm0Ah8QFjNVEXmX-sB6pR-s5D40GI461_K9LvvIfZLbvWWyZDagKJrEfXwgAICl60XxcNyfXuMQU3iBux1BmkV49shIPFfd2f32QByp1DB4/s1600/d5.txt.png)
    
    So the buck stops at `Object.prototype`, and `Function.prototype` is
    a function but proto-inherits from `Object.prototype`.
    
    `Object` and `Function` are both more straightforward:
    both are functions and proto-inherits from `Function.prototype`.
    
    
    ## Literal objects and functions
    Consider the following literal object and function:
    
    ```JavaScript
    var x = {};
    typeof(x); // is an object
    
    var f = function(){};
    typeof(f); // is a function
    ```
    
    So what do they proto-inherit from?
    
    ```JavaScript
    x.__proto__ === Object.prototype; // true
    f.__proto__ === Function.prototype; // true
    ```
    
    ...they proto-inherit not from `Object` or `Function`, but from
    `Object.prototype` or `Function.prototype`.
    
    Remember the general circular relationship between functions and 
    prototype objects? Well `x` is an object, so I suspect we won't
    find it related circularly with its prototype object (if it has one)...
    
    ```JavaScript
    x.prototype === undefined; // true
    ```
    
    But `f` is a function, so let's see if it has a circular relationship
    with its prototype object...
    
    ```JavaScript
    typeof(f.prototype); // is an object
    f.prototype.__proto__ === Object.prototype; // true
    f.prototype.prototype === undefined; // true
    f.prototype.constructor === f; // true, truly circular!
    ```
    
    Thus we see the following relationship `x`, `f`, and the existing circular relationships between `Object`, `Function`, and their prototypes:
    
    ![Relationship between Object, Function, their prototypes, and object x and function f](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiOr45lN9l-LPz9AMjmRLVkvxpfMP54xceqL9mpX7iQwbF-K-haYIV9IZVl5gLH1SjTIr1_iFyhLa39IsuCj0bjOGSVNOa_5DGRf5pNso4fjARMw1TVSCBsHcZ-Q2H_xiggqf3r9fD6Tcw/s1600/d6.txt.png)
    
    
    ## Let's start writing some "classes"
    The goal here is to end up with a "super class" called `SuperKlass`, which will have as a "subclass" the class `Klass`.
    
    ```JavaScript
    var SuperKlass = function(){}; // a constructor for our super "class".
    typeof(SuperKlass.prototype); // is an object.
    
    SuperKlass.__proto__ === Function.prototype; // true
    SuperKlass.prototype.__proto__ === Object.prototype; // true
    
    SuperKlass.prototype.constructor === SuperKlass; // true
    ```
    
    So merely writing a function creates a circular relationship between
    a function and an object:
    
    ![Relationship between Function.prototype and SuperKlass, and Object.prototype and SuperKlass.prototype.](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhgT-GnQ0tXAQtfJOJ02r0Frb7m4lDKOOERu4z07wB4yUbkKL_-yizcD7uQmiPA5tGKiiC6MqJyfn3RawR2hkcFBEgKBRO_PnnjsyGXTo2Orw9V8x3I9VB_ywZ18BRr05pBxX01uA3RmUA/s1600/d7.txt.png)
    
    We'll abbreviate our diagram of the `Function.prototype` and
    `Object.prototype` objects.
    
    
    ```JavaScript
    var Klass = function(){}; // a constructor for another "class"
    ```
    
    As with the `SuperKlass` case above, we get this circular relationship:
    
    ![Relationship between Function.prototype and Klass, and Object.prototype and Klass.prototype.](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiaQWqkD5vVpxmcuwgb_doNxXVcMqTpgnXapMgzO_jGH23z9klsJGGJt1l2sbeJNSeA_SPuDf1BR-EOFuyaaUfcHdoVjatBa9J-8yA6IEiYOFdyWfm-NyF1_93Op3q_eOyQ0kWtkqejt0M/s1600/d8.txt.png)
    
    `Klass` and `SuperKlass` don't look like classes, but they would if we started writing some methods for them.  But we'll hold of on that until we get some class-based inheritance going on first as those two are currently unrelated to each other.
    
    
    ## Proto-inherit our way to writing "subclasses"
    The above don't look like classes yet, but they will once
    we make `Klass` inherit from `SuperKlass`.
    
    ```JavaScript
    var oldKlassProto = Klass.prototype; // for later testing
    
    Klass.prototype = Object.create(SuperKlass.prototype);
    
    Klass.prototype === oldKlassProto; // false. It's really a new object!
    
    Klass.prototype.__proto__ === SuperKlass.prototype; // true
    Klass.prototype.constructor === SuperKlass; // true
    ```
    
    The `Object.create` line of code basically did the following:
    create a new object `o` that proto-inherits
    from `SuperKlass.prototype`, then set `o.constructor` to
    the `constructor` of `SuperKlass.prototype`, which is of course
    just `SuperKlass` because of the circular relationship we saw above!
    
    Then we set `Klass.prototype` to `o` resulting in
    this relationship:
    
    ![Relationship between Klass, Klass.prototype, SuperKlass, SuperKlass.prototype, and Object and Function prototypes, after using Object.create.](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjqAQynhPfRyI9oNlAydARZg9KKtMl8YHVsoShd7rg0xgmW-1BltlZFFlFd80PHe7MWcQzV6DcuT6RD_W_3UwANabRmeBX2clW-6MUeOc-GPi9Z5wGO2euu0F9ZuCV5a6-qMzhhR95aTMo/s1600/d9.txt.png)
    
    Notice the `Klass.prototype.constructor` no longer points back to
    `Klass`, breaking the circular relationship between constructor functions
    and prototypes we kept seeing above.  Let's repair that...
    
    
    ```JavaScript
    Klass.prototype.constructor = Klass;
    ```
    
    ![Relationship after repairing Klass.prototype.constructor to point to Klass](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhwx_vHpDKSwHatiEbKbPKT2ZDJQfz640hWDn9YX1Yb5BndPDqGa2W958oH5CA4rbcoB6cOtzImFMChc704YmcaqqORmBPlnU6sK0EiRi0B00Mpjh36KjCcOdPywCZ2tM3RbzrfXdrftkQ/s1600/d10.txt.png)
    
    Now `Klass` is a subclass inheriting from `SuperKlass` --- inheriting,
    not proto-inheriting.
    
    
    ## Instance method for our Klass and some new objects
    Let's dynamically create a `SuperKlass` instance method:
    
    ```JavaScript
    SuperKlass.prototype.hi = function(){return "super!"};
    ```
    
    Notice where the method is created in the diagram and how it relates to `SuperKlass`, and `Klass`:
    
    ![Relationship after dynamically patching in a "hi" method in SuperKlass.prototype](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjHAC3o2Katyy0MTOTeJXbp6JgtpON3wX3TJVYOc4MJ4Y3aEyau-7NghFiMpNy4nLQoPIXovxvPEZdBwsZUeJi8iW2fuhxduqNX4WFNa1msdLPVwMd3EgukzouQs4kCsphAW7RFHdeqZeM/s1600/d11.txt.png)
    
    We keep making classes but never instance objects constructed
    from those classes, so let's do that now:
    
    ```JavaScript
    var sk = new SuperKlass();
    var k = new Klass();
    
    sk.prototype === undefined; // true
    k.prototype === undefined; // true. They really are just objects
    
    sk.__proto__ === SuperKlass.prototype; // true
    k.__proto__ === Klass.prototype; // true
    ```
    
    So `new F()` just makes a fresh object that proto-inherits from
    `F.prototype`.  In fact, it also runs the `F()` constructor function
    on that fresh object so to initialize it by doing whatever `F` does.
    
    ![Relationship between k and Klass, and sk and SuperKlass.](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEieQZxagZ6zrIBovw4Sg5SE99IrwehtpIKv-M9g4A8Yl4FNXmo3UJV-xRLtweAOCy42N0jgRDycjGULR8bv1G_aKc9EI_GFJcfj5WQPdwd7UnA0Y-_0sKy4TcZZ_u4iEGJzGq0Gzg5oyGM/s1600/d12.txt.png)
    
    ## Polymorphism
    "Polymorphism" here just means, if an object `k` has it, use it,
    otherwise repeat looking for it with the object that `k` 
    proto-inherits from (done recursively, again and again...).
    
    ```JavaScript
    sk.hi(); // "super!"
    ```
    ...note that `sk` itself doesn't have a method `hi()`,
    but `sk.__proto__` (a.k.a. `SuperKlass.prototype`) has it!
    
    ```JavaScript
    k.hi(); // "super!" - polymorphic call to inherited method
    ```
    
    `k` itself doesn't have `hi()`, but in this case,
    `k.__proto__` (a.k.a. `Klass.prototype`) doesn't have it either!
    But `k.__proto__.__proto__`  (a.k.a. `SuperKlass.prototype`)
    does have it!
    
    In effect we've got, in Java terms, an instance method `hi()`
    defined in the `SuperKlass` class, and `Klass` inherits it being
    a subclass.  So `k` is like an instance of the class `Klass`,
    and `sk` is like an instance of the class `SuperKlass`...
    even though JavaScript has no native concept of class or
    class-based inheritance (not until ES6 anyway).
    
    Let's write more methods, this time dynamically adding the `hi` method to `Klass.prototype`:
    
    ```JavaScript
    Klass.prototype.hi = function(){return "klass!"};
    ```
    
    Notice how this `hi` method relates to the `Klass.prototype` object, "overriding" the one proto-inherited from `SuperKlass.prototype`:
    
    ![Relationship after dynamically patching in a "hi" method in Klass.prototype](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiy61cgwO1v0tFIozlgQBaIW_ybFwdD-8kbDrerlsiCoTW5qgnyufyGaA7MMP2Cy6iWO6VthZlGtATpBe8dh1suG8jBsDf28I0lLnkyxb1f2YQnjbG9krKX8JrcvBQ2TscU21-bXugfpkg/s1600/d13.txt.png)
    
    ```JavaScript
    sk.hi(); // "super!"
    k.hi(); // "klass!" - polymorphic call to overriding method
    ```
    
    ...of course `k` itself doesn't have a method `hi()`,
    but `k.__proto__` (a.k.a. `Klass.prototype`) this time does!
    
    Although JavaScript has no native concept of class or class-based 
    inheritance (not until ES6), it kind of half-heartedly does since
    ES3 (JavaScript 1.4) via the `instanceof` operator which basically
    just checks to see if a function's `prototype` is proto-inherited by,
    or is proto-inherited proto-inherited by, or is proto-inherited 
    proto-inherited proto-inherited by, ..., the given object.
    
    ```JavaScript
    sk instanceof Klass; // false
    sk instanceof SuperKlass; // true
    ```
    
    The last line evaluates to `true` because `sk` proto-inherits from `SuperKlass.prototype`
    
    ```JavaScript
    k instanceof Klass; // true
    k instanceof SuperKlass; // also true!
    ```
    
    The last line *also* evaluates to `true` because `k` proto-inherits proto-inherits `SuperKlass.prototype`
    
    Just follow the proto-inheritance hierarchy!
    
    
    ## this and super
    Let's write another subclass.
    
    ```JavaScript
    var Klass2 = function(nm){
        // super(); in Java terms
        SuperKlass.call(this); // call superclass's constructor
                               // with `this` object
        this.name = nm;
    };
    Klass2.prototype = Object.create(SuperKlass.prototype);
    Klass2.prototype.constructor = Klass2;
    
    // Klass2 inherits from SuperKlass via usual proto-inheritance hierarchy:
    Klass2.prototype.__proto__ === SuperKlass.prototype; // true
    
    
    // make a `Klass2` instance
    var k2 = new Klass2("Pat");
    k2.hi(); // "super!" - polymorphic call to inherited method
    
    
    // define a `Klass2` instance method
    Klass2.prototype.hi = function(){return this.name};
    
    sk.hi(); // "super!"
    k.hi(); // "klass!"
    k2.hi(); // "Pat"
    ```
    
    More or less, `this` refers to the object the method is called on, but technically
    it gets tricky as JavaScript's concept of a method is really in terms of functions
    that are stored as properties on objects.  For details, see [MDN's JavaScript reference of this](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this).
    
    Notice the dynamicism of JavaScript, where we added a new instance method to an existing class, and all existing instance objects of that class got to use the newly defined instance method.  No recompilation needed, unlike e.g. Java.
    
    ## References
    It was noted that `__proto__` is deprecated.  It was a way of exposing to 
    us the internal linkages between JavaScript's internal representation of 
    objects.  The "proper" way now is through using the `getPrototypeOf` method.
    See [MDN's reference on Object.prototype.\_\_proto\_\_](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/proto).
    
    A more in-depth explanation of JavaScript OOP can be found at MDN's 
    reference on [Inheritance and the prototype chain](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain) or at [Introduction to Object-Oriented JavaScript](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript).
    
    A hugely more in-depth explanation with beautiful diagrams is available at
    [JavaScript: the core](http://dmitrysoshnikov.com/ecmascript/javascript-the-core).
    Incidentally, had I found that article first, I might never have written
    this one...
    
    ...because I wrote this to help myself understand JavaScript's prototypal OOP system
    by drawing diagrams and playing around with JavaScript in the Firefox Console.
    Conceptually, it was so simple, but then when you actually program with it,
    or when you try to use it in a more class-based manner, it can get confusing.
    
    All diagrams originally drawn with [ASCII Flow](http://asciiflow.com).  Diagrams turned into pretty PNG images using [Shaape](https://github.com/christiangoltz/shaape).
    

    2015-12-21

    Computer Science: a diluted term, soon to be meaningless


    I just saw a grade 6 school teacher's course web page.  He teaches a "Computer Science" course wherein students learned to type and format letters in Microsoft Word and Apple Pages.

    There's a high school teacher who teaches "Computer Science".  His course emphasizes drawing and painting in Photoshop, and animating things in Flash.  Yes, I know you can do a lot of programming in Flash.  No, they don't do very much programming in that course.

    Teachers: Please, don't call typing and formatting a letter in a word processor "Computer Science". Please don't call a multimedia class "Computer Science".  It's confusing students into thinking "Computer Science" is what used to be called "Computer class".

    If your class has a mix of subject matters, call it "Computer class", then within it you can have units on "Business Applications" or "Information Processing", "Multimedia", and maybe even a unit on "Computer Science" (which would only have programming and/or the more "math side" of computer science).

    Otherwise, students will one day step foot in a real Computer Science class, be it in a high school with a real CS focused teacher, or in college or university.  And they're going to go "WTF, this isn't CS", when in fact they were duped in earlier grade school.

    I've seen this happen before in a different subject: engineering.  Schools started offering "engineering" courses that were really just the old electro-technologies courses, which were closer to engineering-technician courses.  Imagine the surprise when some students who took those courses and got into university engineering then faced down the barrage of engineering math and physics courses.

    Actually, who am I kidding.  It's already happening with Computer Science.  The term is meaningless among many junior high students.  Many of them think it's Photoshop, PowerPoint, or photography.

    This is brand dilution.  And it's too late.

    2015-12-20

    Governments mandating which programming language to teach

    Over the years, I've been asked to provide some suggestions regarding what programming language should be mandated by government curriculum for teachers to teach.

    One excuse for having a curriculum mandated programming language is that it'd help teachers with less knowledge tap into a bigger wealth of information as all teachers would be teaching the same language.  Or at least having a main, recommended language would help curricula development, again because everyone would teach the same thing.

    I can't agree with that position.

    The government mandated curriculum should be language and vendor neutral, or else it'll be captured by greed, special interest lobbies, and corporations.  It'll be technologically held back while the rest of the world moves forward until the next curriculum update (in about 10 years time --- that's more than one lifetime in technological progress).

    Of course, the next curriculum update won't change much in the curriculum because of path dependence.  Because so much resources has been created for the old outdated stuff, and so the curriculum would lock in a specific technology for decades at a time even if it gets outdated.

    Do we want to lock into the curriculum for decades at a time: COBOL?  FORTRAN?  C?  Java?  C#?  Python?