Saturday, October 18, 2014

Bird Watching with Clojure -- The Thrush(y)

"With heigh, with heigh, the thrush and the jay,
Are summer songs for me and my aunts
"
Shakespeare, The Winter's Tale
Act IV, Scene III, Lines 10-11

The Thrush


As the wind gently rustles the leaves in the combinator forest.  You sing DO RA and hear sung back to you RA DO.  You sing RA ME and hear ME RA, you sing DO DO and hear DO DO back.  You have just heard the Thrush.




The Thrush or T combinator basically flips your parameters.

T x f = f x

In the Data Aviary Bird package for Haskell it is defined in the following way:

-- | T combinator - thrush.
-- Haskell @(\#)@ in Peter Thiemann\'s Wash, reverse application.
thrush :: a -> (a -> b) -> b
thrush x f = f x

We see that when we call it we pass a value as our first parameter followed by the function we wish to apply the value against.  This is useful when you want to pipe your data through a bunch of functions.

Thrush in F#


In fact in F# this is exactly what the |> (forward pipe) does.  It is defined in the following way:

let (|>) x f = f x

Yep, the forward pipe is nothing more than a Thrush!

Thrush in Joy


In Joy the Thrush goes by the name swap, which makes perfect sense.  It is defined in the following way:

[B] [A] swap == [A] [B]

Thrush in JavaScript


Reg Braithwaite of allong.es fame has a JavaScript library which is perfect for learning combinators called oscin.es.  The Thrush is defined in the following way in oscin.es:

function Thrush (a, b) {
    return b.call(this, a)
  }
  function T (a) { return function _T (b) {
    return b(a)
  }}

This exactly what we would expect looking at the Haskell and F# code above.

This is very similar to how Reginald defined the Thrush in Ruby in his excellent book, Kestrels, Quirky Birds, and Hopelessly Egocentricity:

thrush.call(a_value).call(a_proc)
  => a_proc.call(a_value)

Thrush(y) in Clojure


Clojure has two macros which are Thrushy (Michael Fogus has an excellent post on why they are Thrushy) the -> and ->> macros.

Say we wanted to do the following:

get the sum of the even integers from 1 to 100

We can break this requirement down into a few steps.

  1. get the integers from 1 to 100
  2. get the even integers from 1
  3. sum the integers from 2

What we see happening is a linking or piping of the results of a step down to the next step.

1 to 100 => evens => sum

Here are two ways to write this in Clojure:



The first way looks like a waterfall, but in order to understand it we need to go all the way to the bottom and work are way back up.  In this example we would start with the (range 101) then move up to the (filter even?) and lastly end at the (reduce +).  We find that reading this, we are going against the left to right flow of the code.

The second, Thrush(y) way, the first thing we see is our (range 101), next we find the (filter even?), and last we find the (reduce +).  This way seems very natural as the flow of data agrees with the reading from left to right.

I personally find the pipeline style used in the second way easier to read and use it as often as I can.  Martin Folwer has written an excellent article which goes into collection pipelines in more detail.  Debasish Ghosh has also written about the Thrush in Clojure (which help me a lot when I was trying to understand the -> and ->>macros).



Saturday, October 11, 2014

Try Before You Buy OR REPLs in the Browser

"Now follow – if thou darest – to try whose right"-- Shakespeare, A Midsummer Night's Dream
Act III, Scene II, Line 336

"Can't someone else do it?"
-- Homer Simpsons, Trash of the Titans

One of the hardest things to do is setting up a new programming environment.  Things have improve a lot over the years, but it still be a very daunting task to set up a programming environment for a language you do not even know.  Often in the past I would ask myself, "can't someone else do it?"

Someone else has!  Try a REPL in your browser today!

Luckily many programming environments are waiting for you right now as REPLs in your browser.

A REPL is a Read Evaluate Print Loop, which works how it sounds:

Read input (in the form of code)
Evaluate input
Print result of input
Loop back to top

Today you can now play around with many different programming language from the comfort of your browser by using a REPL.

Here are two that I enjoy:

Clojure instaREPL
Try Haskell!

There is also repl.it which has an impressive collection of languages including: Ruby, Forth, JavaScript, Roy, and even Brainfuck, to name a few.

Clojure instaREPL and Try Haskell! are a bit more like an actual REPL running on your computer than repl.it, but repl.it does offer languages which are not normally associated with REPLs (other than Ruby).

One last thing, while TryAPL is not really a REPL, it is very awesome that you can write APL code with a simulated APL keyboard in your browser!

'Try APL today!'

Sunday, September 28, 2014

How to Get 2 and 4 OR Learning Clojure in Public

"One heart, one bed, two bosoms, and one troth"
-- Shakespeare, A Midsummer Night's Dream
Act II, Scene II, Line 48

I believe in "learning in public" and I've been inspired recently, after watching Uncle Bob's "The Last Programming Language",  going to Strange Loop 2014, and the release of The Joy of Clojure 2nd edition, I've decided to learn me a Clojure for great good.  I've been going through the 4clojure problems as my morning kata for a few weeks now and I've hit problem #52 earlier in the week.

Intro to Destructuring

Let bindings and function parameter lists support destructuring.


(= [2 4] (let [[a b c d e f g] (range)] __))

The answer is [c e] giving the following expression.

(= [2 4] (let [[a b c d e f g] (range)] [c e]))

which evaluates to true
As I understand it, the way this works is that let binding maps the values from range over a through g which gives the a the value 0, b the value 1, c the value of 2, ..., e the value of 4, and so on.  Since we are looking for a vector with the values of 2 and 4, a vector with c and e will give us the [2 4] we are looking for.

How else can we do this?

We could take range, remove the zero value and pipe it through a filter to get just even numbers and then take the 2 and 4.

range -> remove zero -> filter evens -> take first two

In Clojure this would look like this:


(->> (range) (rest) (filter even?) (take 2))

which evaluates to (2 4)

If you want it in a vector you would need to convert the list into a vector which could be done using into, which would look like this:

(->> (range) (rest) (filter even?) (take 2) (into []))

which evaluates to [2 4]

In SQL on SQL Server this would look like this:

DECLARE 
 @min AS INT = 0
,@max AS INT = 100

;WITH [range] AS (
  SELECT @min AS num
  UNION ALL
  SELECT num + 1 FROM [range] WHERE num < @max
)

SELECT TOP 2 *
  FROM [range]
  WHERE num > 0
    AND (num % 2) = 0
;

which gives us the result with a projection containing 2 and 4. 


We are creating a Tally Table using a CTE (as seen in Vinay Pugalia linked blog post), which will gives us similar functionality as the range in Clojure (similar because Clojure's range is lazy loaded and thus can be infinite).  We then filter using the WHERE clause to remove the zero like we do with rest in Clojure, next we filter to just evens using the % operator comparing those results to fine when they equal zero (yes, this not the best way to do this but it is similar).  Last we take the first two results by using TOP with 2.

This is very similar to what I blogged about here on doing FizzBuzz in SQL Server.

There you have it, two different solutions in two different languages on two very different platforms to get the first two even numbers greater than zero.


Learning in public can be fun.

Sunday, September 21, 2014

First Look at the Future OR How Seeing the Wolfram Language Reminded Me of Watching ECW

"Arms, and the man I sing, who, forc'd by fate, 
And haughty Juno's unrelenting hate,
Expell'd and exil'd, left the Trojan shore.
Long labors, both by sea and land, he bore,
And in the doubtful war, before he won
The Latian realm, and built the destin'd town;
His banish'd gods restor'd to rites divine,
And settled sure succession in his line,
From whence the race of Alban fathers come,
And the long glories of majestic Rome.
"
-- The Aeneid, Virgil
Translated by John Dryden
Book I, Lines 1-10

"Wow!" that is what I have down as the main take-away in my notes for Strange Loop 2014's session, "Inside the Wolfram Language".  I walked away feeling, as I believe, Hegel felt as he famously saw Napoleon, "I have just seen the world sprit".*



In a time when designers are aiming for yet smaller and smaller frameworks and languages, Stephan Wolfram proudly shows what one can do if they think different.  The Wolfram Language combines language, algorithms, and data into one complete platform (I can assure you I have not nor expect to get anything for these words), giving the user a lot of power in one console.

What would a Hello World look like in such a language?



Yes, that is both code and execution in a tweet!

That is nice and all but how about something more in-depth?

Here is my own "Hello World" Wolfram Language tweet.



I used the build-in text of the Aeneid and computed a histogram on the length of the words used in the english translation.

Histogram[StringLength[ToLowerCase[ExampleData[{"Text","AeneidEnglish"}, "Words"]]]]

Let's break this line down.

First we get the words of the Aeneid in a data structure.

ExampleData[{"Text","AeneidEnglish"}, "Words"]

Next we convert all the words to lower case so we do not have to worry about "The" not matching "the".

ToLowerCase[ExampleData[{"Text","AeneidEnglish"}, "Words"]]

Then we calculate the length of the different words.

StringLength[ToLowerCase[ExampleData[{"Text","AeneidEnglish"}, "Words"]]]

Last, we graph the data as a histogram.

Histogram[StringLength[ToLowerCase[ExampleData[{"Text","AeneidEnglish"}, "Words"]]]]

Deploy.

CloudDeploy[Histogram[StringLength[ToLowerCase[ExampleData[{"Text","AeneidEnglish"}, "Words"]]]]]

https://www.wolframcloud.com/objects/de6c8dd1-d974-491b-91ca-996fc20af4cc

Done.

Not bad for a one-liner.

Just one more thing, if we tweet to the program to @wolframtap it will tweet back the results.




Very nice.


* Actual text from Hegel's correspondence to Niethammer, "I saw the Emperor -this soul of the world- go out from the city to survey his reign; it is a truly wonderful sensation to see such an individual, who, concentrating on one point while seated on a horse, stretches over the world and dominates it." (as quoted here)

Sunday, September 7, 2014

JavaScript Scopes to Functions Not Files

"The cloud-capped towers, the gorgeous palaces,
The solemn temples, the great globe itself,
Yea, all which it inherit, shall dissolve,
And, like this insubstantial pageant faded,
"Shakespeare, The Tempest
Act IV, Scene I, Lines 152-155

While taking this Pluralsight class by Joe Eames I saw a short demo of how in JavaScript variables are scoped to functions and not to files.  I kind-of-all-ready knew this but have not really looked into it.

Here is a quick demo to show what it means to the browser.


See this Plunker if you want to play around with the code.

The browser loads the index.html file which cause it to load and execute a.js, b.js, and c.js.

  • index.html
    • a.js
    • b.js
    • c.js
The browser executes the JavaScript in the following order.
  1. a.js executes adding the variable a to the global name space (which in the browser is window)
  2. b.js executes calling console.log with the variable a
  3. c.js executes adding the function f to the global name space
  4. c.js then executes the function f (this is called an iffe
    1. which adds the variable x to function f's scope
    2. then calls console.log with the variable x
  5. c.js then tries to call console.log with a variable x but there is not an x in the global name space
With the scope looking like the following.
  • window
    • variable a
      • "this is from a.js"
    • function f
      • variable x
        • "scoped to function f"
Looking at the scope it is easy to see why the call to console.log with a in the file b.js works but the call to console.log with x in the c.js outside of the function f fails.

This is nothing new, but with JavaScript taking off in popularity this is something to keep in mind since it is very different than how most programming languages work.