"Back to our brother of England."
-- Shakespeare, Henry V
Act II, Scene IV, Line 115.1
One of the things I love about functional programming is you can tell a lot about how a function works by just looking at its type signature. In F# 4.0 there is a new function to work with collections, here is it type signature:
('State -> 'T -> 'U * 'State) -> 'State -> C<'T> -> C<'U> * 'State
What do you think it does?
That's right this is a MapFold. Looking at its full definition we see the following:
let mapFold<'T,'State,'Result>
(f:'State -> 'T -> 'Result * 'State) acc list =
How does this work?
Looking at F#'s unit tests we see the following test name:
let ``mapFold works like map + fold`` () =
MapFold works like a map with a fold to maintain state. I know what you are thinking maintaining state is bad, that's why functional programming is easier to reason about. This is very true, but this is not a mutable state, this is an evolving state.
Let us look at an example, the Coin Changer kata:
The Coin Changer kata simulates one of those machines which give you back coins at a store. It takes a list of coin values and the amount of change to be given.
The Coin Changer kata is interesting since it has two things going on at the same time: 1) state and 2) list processing. In the Coin Changer kata you must maintain the amount of change you have left to give along with the amount of each coin to be given back. An example would be 99 cents with an US register, you would get back 3 quarters, 2 dimes, 0 nickels, and 4 pennies.
How would this example of 99 cents with an US register work with MapFold?
changeFor [25; 10; 5; 1] 99
We'll use s to hold the state, r to hold the result, and x to hold the current coin value we are looking at .
Processing the first value: x = 25, s = 99, r = [] resulting in s = 24, r = [3]
Second value: x = 10, s = 24, r = [3] resulting in s = 4, r = [3; 2]
Third: x = 5, s = 4, r = [3; 2] resulting in s = 4, r = [3; 2; 0]
Last: x = 1, s = 4, r = [3; 2; 0] resulting in s = 0, r = [3; 2; 0; 4]
There you have it, step-by-step through the Coin Changer kata using MapFold.
Guess what the source code to MapFold looks for the most part like what we just experienced. Here it is:
We see that it loops through each member of the collection, applying the function given against the state and current member. Once there are no more members it returns a tuple of the result along with the state. For the Coin Changer kata we do not care about the state (maybe we could use it verify that we have 0 cents) so we just drop it and get the result using fst.
There you have it the Coin Changer kata and MapFold seem to be made for each other.
Showing posts with label functional programming. Show all posts
Showing posts with label functional programming. Show all posts
Monday, January 18, 2016
Saturday, November 28, 2015
Axioms of Equal in Clojure
"In quantity equals not one of yours."
-- Shakespeare, Henry IV Part I
Act III, Scene I, Line 93
In The Little Prover we find the following Axioms of Equal:
(dethm equal-same (x)
(equal (equal x x) 't))
(dethm equal-swap (x y)
(equal (equal x y) (equal y x)))
(dethm equal-if (x y)
(if (equal x y
(equal x y)
't)))
I learn best by doing, so I showed myself these axioms in Clojure.
Looking at equal-same we see that if we have something which is the same then those values are equal. Nothing shocking, unless you are using reference equivalence which we are not.
Next we look at equal-swap which states that equivalence is commutative meaning x = y is the same as y = x. Again nothing shocking.
Last we look at equal-if which states that if something is equal once it will be equal again. Note that this assumes that values are immutable which they are (for the most part) in Clojure. This axiom is rather interesting when paired with lazy evaluation, as we see with the following:
(is (true?
(if (= :yep :yep)
(= :yep :yep)
(throw
(IllegalStateException. "How the hell did we get here?")))))
When the statement is evaluated we do not have the Exception thrown! This is a great benefit of the if special form in Clojure. We do see this awesomeness has limits:
(let [x (repeat 42)
y x]
(is (true?
(if (= x y)
(= x y)
false))))
but fails when the infinite sequence is not the same "reference"
(let [x (repeat 42)
y (repeat 42)]
(is (true?
(if (= x y)
(= x y)
false)))))
Despite the second example of comparing with an infinite sequence not finishing, the if special form is awesome and shows the power of the equal-if axiom paired with lazy evaluation.
These axioms are very powerful and I would argue are more useful than tests. If this interests you I would recommend reading The Little Prover or working your way through the flying tour of ACL2.
-- Shakespeare, Henry IV Part I
Act III, Scene I, Line 93
In The Little Prover we find the following Axioms of Equal:
(dethm equal-same (x)
(equal (equal x x) 't))
(dethm equal-swap (x y)
(equal (equal x y) (equal y x)))
(dethm equal-if (x y)
(if (equal x y
(equal x y)
't)))
I learn best by doing, so I showed myself these axioms in Clojure.
Looking at equal-same we see that if we have something which is the same then those values are equal. Nothing shocking, unless you are using reference equivalence which we are not.
Next we look at equal-swap which states that equivalence is commutative meaning x = y is the same as y = x. Again nothing shocking.
Last we look at equal-if which states that if something is equal once it will be equal again. Note that this assumes that values are immutable which they are (for the most part) in Clojure. This axiom is rather interesting when paired with lazy evaluation, as we see with the following:
(is (true?
(if (= :yep :yep)
(= :yep :yep)
(throw
(IllegalStateException. "How the hell did we get here?")))))
When the statement is evaluated we do not have the Exception thrown! This is a great benefit of the if special form in Clojure. We do see this awesomeness has limits:
(let [x (repeat 42)
y x]
(is (true?
(if (= x y)
(= x y)
false))))
but fails when the infinite sequence is not the same "reference"
(let [x (repeat 42)
y (repeat 42)]
(is (true?
(if (= x y)
(= x y)
false)))))
Despite the second example of comparing with an infinite sequence not finishing, the if special form is awesome and shows the power of the equal-if axiom paired with lazy evaluation.
These axioms are very powerful and I would argue are more useful than tests. If this interests you I would recommend reading The Little Prover or working your way through the flying tour of ACL2.
Sunday, November 22, 2015
Axioms of If in Clojure
"How if I answer no?"
-- Shakespeare, Hamlet
Act V, Scene II, Line 167
In The Little Prover we find the following Axioms of If:
(dethm if-true (x y)
(equal (if 't x y) x))
(dethm if-false (x y)
(equal (if 'nil x y) y)
(dethm if-same (x y)
(equal (if x y y) y)
(dethm if-nest-A (x y z)
(if x
(equal (if x y z) y)
't))
(dethm if-nest-E (x y z)
(if x
't
(equal (if x y z) z)))
The way I learn best is bytrying doing, so I showed myself these axioms in Clojure.
Looking at if-true we see that if we have a true premise that we always take the answer part of the if.
(if premise answer else)
This is not a shock to anyone, but is very useful.
Moving on we see if-false states that if we have a false premise that we always take the else part of the if. Again nothing shocking but very useful.
Next we see if-same which states that if the answer and else are the same then the premise does not matter. This makes complete logical sense, but I'll admit I never really thought of it before.
Now let us look at if-nest-A which states that if the condition is true in the premise then it must be true in the answer part. This is very awesome, we can now eliminate code by simply looking for redundant ifs. We see this in the following:
given x is true
(if x
(if x :yep :nope)
:nope)))))
We see that we have the(if what-ever in the outside which matches the (if what-ever in the answer part thus we can eliminate it pulling it up (in the code above the :yep), since if the premise is true on the outside it is true on the inside. This axiom is very useful in refactoring code and I figured it out for myself a long time ago and find myself using it all the time, it is nice to know that it has a solid theoretical basis.
Last we see the anti of if-nest-A, if-nest-E. if-nest-E states that if the condition is false in the premise then it must be false in the else part. We see this in the following:
given x is false
(if x
:nope
(if x :nope :yep))
We see that we have the (if what-ever in the outside which matches the (if what-ever in the else part thus we can eliminate it pulling it up (in the code above the :yep), since if the premise is false on the outside it is false on the inside. Again, this is very useful in eliminating code.
These axioms are very powerful and I would argue are more useful than tests. If this interests you I would recommend reading The Little Prover or working your way through the flying tour of ACL2.
-- Shakespeare, Hamlet
Act V, Scene II, Line 167
In The Little Prover we find the following Axioms of If:
(dethm if-true (x y)
(equal (if 't x y) x))
(dethm if-false (x y)
(equal (if 'nil x y) y)
(dethm if-same (x y)
(equal (if x y y) y)
(dethm if-nest-A (x y z)
(if x
(equal (if x y z) y)
't))
(dethm if-nest-E (x y z)
(if x
't
(equal (if x y z) z)))
The way I learn best is by
Looking at if-true we see that if we have a true premise that we always take the answer part of the if.
(if premise answer else)
This is not a shock to anyone, but is very useful.
Moving on we see if-false states that if we have a false premise that we always take the else part of the if. Again nothing shocking but very useful.
Next we see if-same which states that if the answer and else are the same then the premise does not matter. This makes complete logical sense, but I'll admit I never really thought of it before.
Now let us look at if-nest-A which states that if the condition is true in the premise then it must be true in the answer part. This is very awesome, we can now eliminate code by simply looking for redundant ifs. We see this in the following:
given x is true
(if x
(if x :yep :nope)
:nope)))))
We see that we have the(if what-ever in the outside which matches the (if what-ever in the answer part thus we can eliminate it pulling it up (in the code above the :yep), since if the premise is true on the outside it is true on the inside. This axiom is very useful in refactoring code and I figured it out for myself a long time ago and find myself using it all the time, it is nice to know that it has a solid theoretical basis.
Last we see the anti of if-nest-A, if-nest-E. if-nest-E states that if the condition is false in the premise then it must be false in the else part. We see this in the following:
given x is false
(if x
:nope
(if x :nope :yep))
We see that we have the (if what-ever in the outside which matches the (if what-ever in the else part thus we can eliminate it pulling it up (in the code above the :yep), since if the premise is false on the outside it is false on the inside. Again, this is very useful in eliminating code.
These axioms are very powerful and I would argue are more useful than tests. If this interests you I would recommend reading The Little Prover or working your way through the flying tour of ACL2.
Sunday, November 15, 2015
Axioms of Cons in Clojure
"Why then, build me thy fortunes upon the basis"
-- Shakespeare, Twelfth Night
Act III, Scene II, Line 31
I recently finished The Little Prover. In The Little Prover we find the following Axioms of Con:
(dethm atom/cons (x y)
(equal (atom (cons x y)) 'nil)
(dethm car/cons (x y)
(equal (car (cons x y)) x))
(dethm cdr/cons (x y)
(equal (cdr (cons x y)) y))
(dethm cons/car+cdr (x)
(if (atom x)
't
(equal (cons (car x) (cdr x)) x)))
The way I learn best is by showing myself that something makes sense, so I went through showing myself these axioms in Clojure.
Looking at atom/cons in the code above we see that Clojure does not have atom but (complement sequential?) is close enough if we are working with sequential collections so we'll use that. Using the definition that an atom is not a sequential collection we see in the code above that cons "always" yields not an atom.
Next looking at car/cons in the code above we see that using first (Clojure's car) on a cons "always" yields the head of the sequential collection, which makes prefect sense since that is what one expects from first.
The other side of car/cons is cdr/cons. Looking at the code above we see that using rest (Clojure's cdr) on a cons "always" yields the tail of the sequential collection, which again makes prefect sense since that is what one expects from rest.
Last we look at cons/car+cdr. Looking at the code we see that if we do not have an atom that first and rest (Clojure's car and cdr) together yield the sequential collection, which again is what one would expect.
So what does any of this give us? We now have a firm foundation on which to define other theorems and proofs about our statements using these axioms as our basis. This is very powerful and I would argue that this is better having tests.
If this interests you I would recommend reading The Little Prover or working your way through the flying tour of ACL2.
-- Shakespeare, Twelfth Night
Act III, Scene II, Line 31
I recently finished The Little Prover. In The Little Prover we find the following Axioms of Con:
(dethm atom/cons (x y)
(equal (atom (cons x y)) 'nil)
(dethm car/cons (x y)
(equal (car (cons x y)) x))
(dethm cdr/cons (x y)
(equal (cdr (cons x y)) y))
(dethm cons/car+cdr (x)
(if (atom x)
't
(equal (cons (car x) (cdr x)) x)))
The way I learn best is by showing myself that something makes sense, so I went through showing myself these axioms in Clojure.
Looking at atom/cons in the code above we see that Clojure does not have atom but (complement sequential?) is close enough if we are working with sequential collections so we'll use that. Using the definition that an atom is not a sequential collection we see in the code above that cons "always" yields not an atom.
Next looking at car/cons in the code above we see that using first (Clojure's car) on a cons "always" yields the head of the sequential collection, which makes prefect sense since that is what one expects from first.
The other side of car/cons is cdr/cons. Looking at the code above we see that using rest (Clojure's cdr) on a cons "always" yields the tail of the sequential collection, which again makes prefect sense since that is what one expects from rest.
Last we look at cons/car+cdr. Looking at the code we see that if we do not have an atom that first and rest (Clojure's car and cdr) together yield the sequential collection, which again is what one would expect.
So what does any of this give us? We now have a firm foundation on which to define other theorems and proofs about our statements using these axioms as our basis. This is very powerful and I would argue that this is better having tests.
If this interests you I would recommend reading The Little Prover or working your way through the flying tour of ACL2.
Sunday, November 8, 2015
Showing Map Distributes Over Functional Composition OR Fun With Clojure
"Here by the cheeks I'll drag thee up and down."
-- Shakespeare, Henry VI Part 1
Act I, Scene III, Line 51
I love to try things out for myself. Whenever I am trying to understand idea I need to show myself that the idea is valid. Sometimes I will just accept something, but if I really want to understand it I will show myself that it makes sense.
While rereading Dr. Hutton's paper "A tutorial on the universality and expressiveness of fold", I came back across the following statement, "the map operator distributes over function composition". Being the kind of person which likes to show things to myself I figured I'd show myself this idea in Clojure as part of my daily kata.
Looking at the code above we see the following:
So what does this give us? Having this property we are allowed to improve the performance of our code by composing a series of transformation against a collection to a single transformation of the collection dragged through a series of composed functions. In fact this is the whole idea behind streams.
Taken straight from Raoul-Gabriel Urma's article in Java Magazine, "[i]n a nutshell, collections are about data and streams are about computations." Thinking about processing as a series of computation we see how we can naturally think about composing our computations together and then drag the data through using a higher order function like map to preform the series of transformations in one pass.
-- Shakespeare, Henry VI Part 1
Act I, Scene III, Line 51
I love to try things out for myself. Whenever I am trying to understand idea I need to show myself that the idea is valid. Sometimes I will just accept something, but if I really want to understand it I will show myself that it makes sense.
While rereading Dr. Hutton's paper "A tutorial on the universality and expressiveness of fold", I came back across the following statement, "the map operator distributes over function composition". Being the kind of person which likes to show things to myself I figured I'd show myself this idea in Clojure as part of my daily kata.
Looking at the code above we see the following:
- map f · map g = map (f · g)
- r/map f · r/map g = r/map (f · g)
- reduction f · reduction g = reduction (f · g)
So what does this give us? Having this property we are allowed to improve the performance of our code by composing a series of transformation against a collection to a single transformation of the collection dragged through a series of composed functions. In fact this is the whole idea behind streams.
Taken straight from Raoul-Gabriel Urma's article in Java Magazine, "[i]n a nutshell, collections are about data and streams are about computations." Thinking about processing as a series of computation we see how we can naturally think about composing our computations together and then drag the data through using a higher order function like map to preform the series of transformations in one pass.
Sunday, October 18, 2015
On the Fusion Property of Fold
"If I break time, or flinch in property"
-- Shakespeare, All's Well That Ends Well
Act II, Scene I, Line 187
In Dr. Hutton's excellent paper, "A tutorial on the universality and expressiveness of fold", he gives the following definition of the fusion property of Fold:
h · fold g w = fold f v
Great, but what does this mean to me? Well if we go on in the paper we find the following application of the fusion property of Fold:
(+1) · sum = fold (+) 1
Interesting, we see that adding 1 to the sum (defined as, fold (+) 0) of a collection is the same as folding over that collection with 1 as the seed value. Further down in the paper we see that we can simplify and generalize the application above as:
(⊕ a) · fold (⊕) b = fold (⊕) (b ⊕ a)
Now this is really cool. We can apply an associative binary operation with a value against the results of folding that operation against a collection is the same as applying that binary operation with a value against the seed.
As an aside, an associative binary operation is an operation which takes two values from the same type and outputs a value of that type, examples would be +, -, *, /, min, max, ... We say an operation is associative if and only if:
a ⊕ b = b ⊕ a
This means addition is associative while subtraction is not (2 - 1 != 1 - 2, but 2 + 1 = 1 + 2).
How about looking at some examples of the fusion property?
First we'll look at examples in Clojure.
We see in the Clojure example that we are using reduce to fold over a collection of integers (integers are easier to use in examples but this idea is not limited to integers) applying an associative binary operation against each member. We see that applying the operation with a value against the result is the same as applying that operation and value against the seed.
Next we'll look at examples in ECMAScript 2015 (JavaScript) using Immutable.js.
We see in the ECMAScript example that we are using Immutable's reduce to fold over a List of integers (again this could be applied against any type) applying the associative binary operation against the members. Like the Clojure example we see that applying the operation with a value against the result is the same as applying that operation and value against the seed.
We can go further with this idea but I feel this is a good overview of the concept.
-- Shakespeare, All's Well That Ends Well
Act II, Scene I, Line 187
In Dr. Hutton's excellent paper, "A tutorial on the universality and expressiveness of fold", he gives the following definition of the fusion property of Fold:
h · fold g w = fold f v
Great, but what does this mean to me? Well if we go on in the paper we find the following application of the fusion property of Fold:
(+1) · sum = fold (+) 1
Interesting, we see that adding 1 to the sum (defined as, fold (+) 0) of a collection is the same as folding over that collection with 1 as the seed value. Further down in the paper we see that we can simplify and generalize the application above as:
(⊕ a) · fold (⊕) b = fold (⊕) (b ⊕ a)
Now this is really cool. We can apply an associative binary operation with a value against the results of folding that operation against a collection is the same as applying that binary operation with a value against the seed.
As an aside, an associative binary operation is an operation which takes two values from the same type and outputs a value of that type, examples would be +, -, *, /, min, max, ... We say an operation is associative if and only if:
a ⊕ b = b ⊕ a
This means addition is associative while subtraction is not (2 - 1 != 1 - 2, but 2 + 1 = 1 + 2).
How about looking at some examples of the fusion property?
First we'll look at examples in Clojure.
We see in the Clojure example that we are using reduce to fold over a collection of integers (integers are easier to use in examples but this idea is not limited to integers) applying an associative binary operation against each member. We see that applying the operation with a value against the result is the same as applying that operation and value against the seed.
Next we'll look at examples in ECMAScript 2015 (JavaScript) using Immutable.js.
We see in the ECMAScript example that we are using Immutable's reduce to fold over a List of integers (again this could be applied against any type) applying the associative binary operation against the members. Like the Clojure example we see that applying the operation with a value against the result is the same as applying that operation and value against the seed.
We can go further with this idea but I feel this is a good overview of the concept.
Sunday, October 11, 2015
Folding Up the Coin Changer Kata
"Whate'er the course, the end is the renown."
-- Shakespeare, All's Well That Ends Well
Act IV Scene IV, Line 36
The Coin Changer kata has three things which make it a good kata.
The user story is very simple:
Given a collection of coins of different denominational value
When an amount of change is given
Then it will give back the number of coins for each denomination needed using the least amount of coins possible
A type signature for the function needed could look like the following:
changeFor(coins: int[], amount: int): int[]
We are expecting an array of integers which have different denomination of coins (in the US something like: [25, 10, 5, 1]) and the amount of change needed (something like: 99) giving a resulting array of integers showing how many of each denomination (something like: [3, 2, 0, 4]).
What would we need to be able to do this kata using just Fold?
We'll need to use a tuple (or something like one) to manage the state of the amount of change needed and the resulting array of integers.
Now lets look at an example using a typical full US register with quarters, dimes, nickels, and pennies. We'll look at getting change for 99 cents.
First Memorize has (99, empty) and X has 25 giving the result of (24, [3]).
Next Memorize has (24, [3]) and X has 10 giving the result of (4, [3, 2]).
Then Memorize has (4, [3, 2]) and X has 5 giving the result of (4, [3, 2, 0]).
Last Memorize has (4, [3, 2, 0]) and X has 1 giving the result of (0, [3, 2, 0, 4]).
Finally obtaining the tuple item with the resulting array of integers to get the change.
We see with the Clojure code that we seed with a map with a key for the :amount and one for the :result. We fold over the coins using reduce destructing the memoize value into the amount and result. We then just calculate the new amount using: amount % coin, follow by inserting the number of coins we get using: amount / coin. We use cons to show off the coolness that is the thread-last macro (at least that is why I think I coded it this way, it was a little bit ago that I did the gist and I cannot remember why I code with cons over conj).
We see with the C# code that we seed using a Tuple (which I think has very ugly syntax in C#). We then fold over the coins using aggregate just like the Clojure code above. We calculate the changer results and place them into a new Tuple which we return as the memoize.
In this ECAMScript 2015 example we use lodash's foldl to fold over the coins just like the two examples above. The seed value is a simple JavaScript object with the members of amount and result given. We are a bit dirty and mutate the memoize on each call with the changer results but we could argue that this is still "pure" since the mutation happens to an item which is created and used only in side the function.
Last we look at Facebook's open source Immutable.js. We create an immutable List with the coins which we use to fold over the values using reduce. The seed value we give it is a simple JavaScript array with an immutable List to hold the results and the amount passed in. We could use an immutable Map if we wanted to keep it purely immutable. Like this:
I am not a huge fan of stringly typed accessors, but I understand why they use them. Both ways are good and would really come down to to performance and readability.
Thus ends our tour of All You Need is Fold, but this is not the end of the uses of Fold, for Fold is universal.
-- Shakespeare, All's Well That Ends Well
Act IV Scene IV, Line 36
Coin Changer Kata
The Coin Changer kata has three things which make it a good kata.
- easy to understand
- rich set of features
- lots of realistic possible implementations
The user story is very simple:
Given a collection of coins of different denominational value
When an amount of change is given
Then it will give back the number of coins for each denomination needed using the least amount of coins possible
A type signature for the function needed could look like the following:
changeFor(coins: int[], amount: int): int[]
We are expecting an array of integers which have different denomination of coins (in the US something like: [25, 10, 5, 1]) and the amount of change needed (something like: 99) giving a resulting array of integers showing how many of each denomination (something like: [3, 2, 0, 4]).
What would we need to be able to do this kata using just Fold?
We'll need to use a tuple (or something like one) to manage the state of the amount of change needed and the resulting array of integers.
Now lets look at an example using a typical full US register with quarters, dimes, nickels, and pennies. We'll look at getting change for 99 cents.
First Memorize has (99, empty) and X has 25 giving the result of (24, [3]).
Next Memorize has (24, [3]) and X has 10 giving the result of (4, [3, 2]).
Then Memorize has (4, [3, 2]) and X has 5 giving the result of (4, [3, 2, 0]).
Last Memorize has (4, [3, 2, 0]) and X has 1 giving the result of (0, [3, 2, 0, 4]).
Finally obtaining the tuple item with the resulting array of integers to get the change.
Clojure
We see with the Clojure code that we seed with a map with a key for the :amount and one for the :result. We fold over the coins using reduce destructing the memoize value into the amount and result. We then just calculate the new amount using: amount % coin, follow by inserting the number of coins we get using: amount / coin. We use cons to show off the coolness that is the thread-last macro (at least that is why I think I coded it this way, it was a little bit ago that I did the gist and I cannot remember why I code with cons over conj).
C#
We see with the C# code that we seed using a Tuple (which I think has very ugly syntax in C#). We then fold over the coins using aggregate just like the Clojure code above. We calculate the changer results and place them into a new Tuple which we return as the memoize.
ECMAScript 2015
In this ECAMScript 2015 example we use lodash's foldl to fold over the coins just like the two examples above. The seed value is a simple JavaScript object with the members of amount and result given. We are a bit dirty and mutate the memoize on each call with the changer results but we could argue that this is still "pure" since the mutation happens to an item which is created and used only in side the function.
ECMAScript 2015 and Immutable.js
Last we look at Facebook's open source Immutable.js. We create an immutable List with the coins which we use to fold over the values using reduce. The seed value we give it is a simple JavaScript array with an immutable List to hold the results and the amount passed in. We could use an immutable Map if we wanted to keep it purely immutable. Like this:
I am not a huge fan of stringly typed accessors, but I understand why they use them. Both ways are good and would really come down to to performance and readability.
The End
Thus ends our tour of All You Need is Fold, but this is not the end of the uses of Fold, for Fold is universal.
Sunday, October 4, 2015
Fold the Zip Up
"They fell together all, as by consent."
-- Shakespeare, The Tempest
Act II, Scene I, Line 207
Zip can be thought of as the more generic form of Map. Think of Zip as applying a function against each member of the collections given to it, thus mapping more than one collection to another collection. It is a lot easier to see than to explain in words.
I believe Zip2 would get the following definition:
zip2 :: (α → β → γ) → ([α] → [β] → [γ])
zip2 f = fold (λx y xs ys → f x y : xs ys) [ ]
This would be if we limit Zip to being used on 2 collections (this is mine definition, Dr. Graham Hutton has nothing to do with this definition, blame me if it is wrong).
Folding a Zip we'll need a collection to seed with then we just apply the given function against each member from each collection concatenating it with the seed, just as we did with Map.
Next we'll look at a simple example adding the members of two collections together.
First Memoize has nothing and X has 1 while Y has 10 giving the result of 11.
Next Memoize has 11 and X has 2 while Y has 20 giving the result of 11, 22.
Lets see some code examples.
With Clojure we do not have to worry about the number of collection we'll give our Zip function since we can use destructing to say and everything else. We can then apply map to create a vector containing all the elements next to each other, we'll see this is common in the other languages since the implementation of reduce is only design to work with a single collection. From here it is just like Map except that we need to use apply since are members are a collection themselves.
With C# we have to specify the number of collection we are going to Zip, in this case we'll do two. We need to Zip the members from the two collections together into a Tuple (which is a bit of cheating but I can find no other way to do it with LINQ). From there it is just like Map. With this implementation we do have a limitation in that the two collections must be the same size, since to get around that would be a bit of work and we rather have a readable implementation than perfect code.
In ECMAScript 2015 (also known as JavaScript ES6), we see an implementation similar to the C# code except we use lodash's zip to place the members in a single collection (lodash's zipWith is like LINQ's Zip). From there it is just like Map. With this implementation like the C# implementation we have a limitation in that the two collections must be the same size, and again the work around would be a lot of work so we'll error on keeping the code readable.
There you have it showing once again that all you need is Zip.
-- Shakespeare, The Tempest
Act II, Scene I, Line 207
Zip
Zip can be thought of as the more generic form of Map. Think of Zip as applying a function against each member of the collections given to it, thus mapping more than one collection to another collection. It is a lot easier to see than to explain in words.
I believe Zip2 would get the following definition:
zip2 :: (α → β → γ) → ([α] → [β] → [γ])
zip2 f = fold (λx y xs ys → f x y : xs ys) [ ]
This would be if we limit Zip to being used on 2 collections (this is mine definition, Dr. Graham Hutton has nothing to do with this definition, blame me if it is wrong).
Folding a Zip we'll need a collection to seed with then we just apply the given function against each member from each collection concatenating it with the seed, just as we did with Map.
Next we'll look at a simple example adding the members of two collections together.
First Memoize has nothing and X has 1 while Y has 10 giving the result of 11.
Next Memoize has 11 and X has 2 while Y has 20 giving the result of 11, 22.
Lets see some code examples.
Clojure
With Clojure we do not have to worry about the number of collection we'll give our Zip function since we can use destructing to say and everything else. We can then apply map to create a vector containing all the elements next to each other, we'll see this is common in the other languages since the implementation of reduce is only design to work with a single collection. From here it is just like Map except that we need to use apply since are members are a collection themselves.
C#
With C# we have to specify the number of collection we are going to Zip, in this case we'll do two. We need to Zip the members from the two collections together into a Tuple (which is a bit of cheating but I can find no other way to do it with LINQ). From there it is just like Map. With this implementation we do have a limitation in that the two collections must be the same size, since to get around that would be a bit of work and we rather have a readable implementation than perfect code.
ECMAScript 2015
In ECMAScript 2015 (also known as JavaScript ES6), we see an implementation similar to the C# code except we use lodash's zip to place the members in a single collection (lodash's zipWith is like LINQ's Zip). From there it is just like Map. With this implementation like the C# implementation we have a limitation in that the two collections must be the same size, and again the work around would be a lot of work so we'll error on keeping the code readable.
Done
There you have it showing once again that all you need is Zip.
Labels:
C#,
clojure,
es6,
functional programming,
Javascript,
lodash,
tdd,
zip
Sunday, September 13, 2015
Filter, Guarding You From Fold
"You and your ways; whose wraths to guard you from,"
A simple example would be a filtering with a function which says if a value is odd or not.
-- Shakespeare, The Tempest
Filter
Filter is a lot like a higher order functional bouncer, it prevents undesirable elements from getting into the resulting collection.
A simple example would be a filtering with a function which says if a value is odd or not.
In Dr. Hutton's excellent paper, "A tutorial on the universality and expressiveness of fold", he gives the following definition of Filter in terms of Fold:
filter :: (α → Bool) → ([α] → [α])
filter p = fold (λx xs → if p x then x : xs else xs) [ ]
From the definition above, we see that Filter is just Map but with a predicate clause stating if the element should be placed in the resulting collection or not.
Let us look at an example using my name Mike and a function which will check if a character is lower case.
(similar to Map last time)
First Memoize has nothing and X has M.
Next Memoize still has nothing (since M is upper case) and X has i.
Now Memoize has i and X has k.
Then Memoize has i and k while X has e.
Now the Filter will return the result of "ike".
Now what we all came to see, some code examples.
Clojure
In Clojure we can use the reduce function to move through the collection checking the predicate condition with the if macro guard against undesirable elements.
C#
With the C# code we'll need to create some type of collection with the seed value which will allow us to add elements to it, we'll use the collection class of List. We'll simply iterate through the collection using Aggregate and add elements to the memoize List if they pass the predicate clause.
ECMAScript 2015
In the code above that we'll use the build in JavaScript array method of push to add an element which gets past the guarding predicate function to the array at the end. We are simply move through the collection we are filtering, pushing elements into the memoize array.
Fin
There you have it we are able to keep the riffraff elements out using Fold.
Monday, September 7, 2015
Folding into Map
"I have forgot the map."
-- Shakespeare, Henry IV Part I
Act III, Scene I, Line 5
Map is the first of the big three Higher Order Function we will looking at Folding using Dr. Hutton's excellent paper, "A tutorial on the universality and expressiveness of fold", as a guide. The idea of a Map is simple, you have a collection which you wish to apply some translation function against every member of the collection.
We can look at a few simple examples, the first of which would be the identity function.
Next we can look at a constant function which maps turtle for any value given to it.
Last we can look at a function which shifts everything given to it.
All of this these functions have something in common, they all apply a function against every single member of the collection they are given, thus the resulting collection is the exact same size as the collection given to it.
We can now look at how we would implement Map using a Fold. We see that Dr. Hutton gives Map the following definition:
map :: (α → β) → ([α] → [β])
map f = fold (λx xs → f x : xs) [ ]
Folding a Map we'll need a collection to seed with then we just apply the given function against each member concatenating it with the seed.
(similar to Reverse from last time)
Let us look at an example of upper casing Mike.
First Memoize has nothing and X has M.
Second Memoize has M and X has i.
Third time Memoize has MI and X has k.
Finally Memoize has MIK and X has e.
Giving the final result of MIKE. Now let us look at some code examples.
In Clojure we use the reduce function to Fold. We give the reduce a seed of an empty collection and use conj to join applying the function given with the resulting collection.
With C# we use the aggregate LINQ function to Fold. We give the aggregate a List and add the result of applying each member of the given collection against the function we are mapping with.
Using ECMAScript 2015 (aka JavaScript), we use lodash's foldl to Fold. We give the foldl an empty array and push the result of applying the function given against the member we are mapping against.
There you have it by folding with an empty collection and applying the given function against each member adding the result against the seed and you have a Map.
-- Shakespeare, Henry IV Part I
Act III, Scene I, Line 5
Map
Map is the first of the big three Higher Order Function we will looking at Folding using Dr. Hutton's excellent paper, "A tutorial on the universality and expressiveness of fold", as a guide. The idea of a Map is simple, you have a collection which you wish to apply some translation function against every member of the collection.
We can look at a few simple examples, the first of which would be the identity function.
Next we can look at a constant function which maps turtle for any value given to it.
Last we can look at a function which shifts everything given to it.
All of this these functions have something in common, they all apply a function against every single member of the collection they are given, thus the resulting collection is the exact same size as the collection given to it.
We can now look at how we would implement Map using a Fold. We see that Dr. Hutton gives Map the following definition:
map :: (α → β) → ([α] → [β])
map f = fold (λx xs → f x : xs) [ ]
Folding a Map we'll need a collection to seed with then we just apply the given function against each member concatenating it with the seed.
(similar to Reverse from last time)
Let us look at an example of upper casing Mike.
First Memoize has nothing and X has M.
Second Memoize has M and X has i.
Third time Memoize has MI and X has k.
Finally Memoize has MIK and X has e.
Giving the final result of MIKE. Now let us look at some code examples.
Clojure
In Clojure we use the reduce function to Fold. We give the reduce a seed of an empty collection and use conj to join applying the function given with the resulting collection.
C#
With C# we use the aggregate LINQ function to Fold. We give the aggregate a List and add the result of applying each member of the given collection against the function we are mapping with.
ECMAScript 2015
Using ECMAScript 2015 (aka JavaScript), we use lodash's foldl to Fold. We give the foldl an empty array and push the result of applying the function given against the member we are mapping against.
To End All
There you have it by folding with an empty collection and applying the given function against each member adding the result against the seed and you have a Map.
Saturday, August 29, 2015
Displanting a Function OR Folding a Reverse
"Displant a town, reverse a prince's doom"
-- Shakespeare, Romeo and Juliet
Act III, Scene III, Line 60
The interesting thing about the Reverse function is that it is not really doing anything. With a small clerical error in a visit and recombine function you have reverse.
In Dr. Hutton's excellent paper, "A tutorial on the universality and expressiveness of fold", the following definition is given for reversing:
reverse :: [α] → [α]
reverse = fold (λx xs → xs ++ [x]) [ ]
We see that we concat the memoize with the member, in that order, thus reversing the collection.
Since I like advertising myself, let us go through an example with my name (someone has to advertise for me).
First time the Memoize has nothing and X has M.
Second time the Memoize has M and X is i.
Third time Memoize has i and M and X has k.
Fourth time Memoize has k, i, and M while X has e.
Leaving us with ekiM.
Let us look at some code examples.
We see with the Clojure code we are using the cons function to place the current member in the front of the memoize. We do this for the whole collection thus giving us the collection in reverse.
With the C# code we see that we need to create something to contain the resulting collection, in this case we'll create a List. We create the reversed collection in an immutable way by creating a new List every time in the lambda.
With JavaScript (ECMAScript 2015) we us the unshift method on the array. Since unshift returns the length of the array after the member is added to the head of the array (which I totally did not expect) we need to manually return the memoize after applying unshift.
There you have it again, yet another function which can be created using Fold. Showing once again that all you need is Fold.
-- Shakespeare, Romeo and Juliet
Act III, Scene III, Line 60
Reverse
The interesting thing about the Reverse function is that it is not really doing anything. With a small clerical error in a visit and recombine function you have reverse.
In Dr. Hutton's excellent paper, "A tutorial on the universality and expressiveness of fold", the following definition is given for reversing:
reverse :: [α] → [α]
reverse = fold (λx xs → xs ++ [x]) [ ]
We see that we concat the memoize with the member, in that order, thus reversing the collection.
Since I like advertising myself, let us go through an example with my name (someone has to advertise for me).
First time the Memoize has nothing and X has M.
Second time the Memoize has M and X is i.
Third time Memoize has i and M and X has k.
Fourth time Memoize has k, i, and M while X has e.
Leaving us with ekiM.
Let us look at some code examples.
Clojure
We see with the Clojure code we are using the cons function to place the current member in the front of the memoize. We do this for the whole collection thus giving us the collection in reverse.
C#
With the C# code we see that we need to create something to contain the resulting collection, in this case we'll create a List. We create the reversed collection in an immutable way by creating a new List every time in the lambda.
ECMAScript 2015
With JavaScript (ECMAScript 2015) we us the unshift method on the array. Since unshift returns the length of the array after the member is added to the head of the array (which I totally did not expect) we need to manually return the memoize after applying unshift.
Fin
There you have it again, yet another function which can be created using Fold. Showing once again that all you need is Fold.
Sunday, August 23, 2015
Think About Length OR How Fold Can Do Everything, Even Count
"Leave nothing out for length, and make us think"
-- Shakespeare, Coriolanus
Act II, Scene II, Line 47
length :: [α] → Int
length = fold (λx n → 1 + n) 0
We see with this definition we do nothing with the current member of the collection (x above) and instead only act on the memoize (n above).
In the simple example below we will see that the string "Mike" has 4 characters in it.
At the start we have a Seed of 0 and a collection with the members M, i, k, and e.
First time Memoize has 0 in it and X has M.
Second time Memoize has 1 in it and X has i.
Third time Memoize has 2 in it and X has the letter k.
Last time Memoize has 3 and X has e.
There you have it (maybe I should have used my sister Kim name instead). Let us see some code.
We see in the clojure example that function we give the reduce must have two parameters, so we call the second one _ to denote that it is not used.
With the C# code the lambda we give Aggregate has two values of which we give the second one the name of _ to denote not using it.
With ECMAScript 2015 we use lodash's foldl and see that the lambda only has to have one value which is the memoize.
-- Shakespeare, Coriolanus
Act II, Scene II, Line 47
How Long is It?
I am not sure why but before I start reading a chapter or watching something I've recorded I almost always check to see how long it is. Today's post will be using Fold to find the length of a collection. In Dr. Hutton's excellent paper, "A tutorial on the universality and expressiveness of fold", the following definition is given for finding the length:length :: [α] → Int
length = fold (λx n → 1 + n) 0
We see with this definition we do nothing with the current member of the collection (x above) and instead only act on the memoize (n above).
In the simple example below we will see that the string "Mike" has 4 characters in it.
At the start we have a Seed of 0 and a collection with the members M, i, k, and e.
First time Memoize has 0 in it and X has M.
Second time Memoize has 1 in it and X has i.
Third time Memoize has 2 in it and X has the letter k.
Last time Memoize has 3 and X has e.
There you have it (maybe I should have used my sister Kim name instead). Let us see some code.
Clojure
We see in the clojure example that function we give the reduce must have two parameters, so we call the second one _ to denote that it is not used.
C#
With the C# code the lambda we give Aggregate has two values of which we give the second one the name of _ to denote not using it.
JavaScript (ECMAScript 2015)
With ECMAScript 2015 we use lodash's foldl and see that the lambda only has to have one value which is the memoize.
Fin
There you have it counting with Fold, showing that you need is Fold.Sunday, August 16, 2015
If True or False I Know Not
"I idly heard; if true or false I know not."
-- Shakespeare, King John
Act IV, Scene II, Line 124
This is the next in the series of post on Dr. Graham Hutton's excellent paper, "A tutorial on the universality and expressiveness of fold", this time around we'll look at Oring. Dr. Hutton has given Oring the following definition:
or :: [Bool] → Bool
or = fold (∨) False
The idea is that we Fold an Or function with a seed value of False. If one of the members of the collection is True we Or it with False giving us True, else if none of the members of the collection are True we will end up with the value of False.
In the simple example below we'll see that if we have a single value of True then the end result will be True.
At the start we have a Seed value of False with collection containing False, True, and False.
Let us now look at this in sweet, sweet code.
In the Clojure code that we use the or macro and a seed value of false in order to create an Oring function using the higher order function of reduce. Since reduce is expecting a function and not a macro we need to create a lambda function to wrap the or macro.
We see in the C# code that we can use the LINQ aggregate method on the collection we are folding. We give the aggregate a seed value of false and in the lambda we simply takes the memorize and the current member and or them.
Using lodash's foldl function along with Babel.js we are able to create an Oring function by folding over the collection and passing it to a lambda function which ors the current member of the collection with the memorize value. We give a seed value of false thus causing the initial value of the memorize to be false.
There you have it an Oring function using nothing but Fold. Thus "proving" that all you need is Fold.
Act IV, Scene II, Line 124
Welcome Back
This is the next in the series of post on Dr. Graham Hutton's excellent paper, "A tutorial on the universality and expressiveness of fold", this time around we'll look at Oring. Dr. Hutton has given Oring the following definition:
or :: [Bool] → Bool
or = fold (∨) False
The idea is that we Fold an Or function with a seed value of False. If one of the members of the collection is True we Or it with False giving us True, else if none of the members of the collection are True we will end up with the value of False.
In the simple example below we'll see that if we have a single value of True then the end result will be True.
At the start we have a Seed value of False with collection containing False, True, and False.
First time the Memorize has False and X has False.
Second time the Memorize has False and X has True.
Third time the Memorize has True and X has False giving use the finally value of True.
Let us now look at this in sweet, sweet code.
Clojure
In the Clojure code that we use the or macro and a seed value of false in order to create an Oring function using the higher order function of reduce. Since reduce is expecting a function and not a macro we need to create a lambda function to wrap the or macro.
C#
We see in the C# code that we can use the LINQ aggregate method on the collection we are folding. We give the aggregate a seed value of false and in the lambda we simply takes the memorize and the current member and or them.
JavaScript (ECMAScript 2015)
Using lodash's foldl function along with Babel.js we are able to create an Oring function by folding over the collection and passing it to a lambda function which ors the current member of the collection with the memorize value. We give a seed value of false thus causing the initial value of the memorize to be false.
Until Next Time
There you have it an Oring function using nothing but Fold. Thus "proving" that all you need is Fold.
Sunday, August 9, 2015
Approaching the Fold
"Approach the fold and cull th' infected forth"
-- Shakespeare, Timon of Athens
Act V, Scene IV, Line 43
In Graham Hutton's excellent paper, "A tutorial on the universality and expressiveness of fold", the first function that is looked at is And. Dr. Hutton gives And the following definition:
and :: [Bool] → Bool
and = fold (∧) True
The idea being that we give Fold an And function with a seed value of True. If one of the members of the collection given is False the Anding it with True will yield a value of False and thus the end result will be False. If no member of the collection given is False then the end result will be True.
Let us look at this in code.
To create an Anding function we'll use reduce along with the and macro with a seed of true. Since and is a macro, we'll need to wrap it in a function in order to be able to use it in reduce.
We'll use the LINQ function Aggregate along && and a value of true to create an Anding function.
We see that by using lodash's foldl function with && and the value true we can create an Anding function.
Since we live in the future, we'll use Babel to allow us to use ECMAScript 2015. We see again that by using lodash's foldl with && along with the value true we now have an Anding function.
There you have it the And function using Fold, showing once again that all you need is Fold.
-- Shakespeare, Timon of Athens
Act V, Scene IV, Line 43
Welcome
In Graham Hutton's excellent paper, "A tutorial on the universality and expressiveness of fold", the first function that is looked at is And. Dr. Hutton gives And the following definition:
and :: [Bool] → Bool
and = fold (∧) True
The idea being that we give Fold an And function with a seed value of True. If one of the members of the collection given is False the Anding it with True will yield a value of False and thus the end result will be False. If no member of the collection given is False then the end result will be True.
Let us look at this in code.
Clojure
To create an Anding function we'll use reduce along with the and macro with a seed of true. Since and is a macro, we'll need to wrap it in a function in order to be able to use it in reduce.
C#
We'll use the LINQ function Aggregate along && and a value of true to create an Anding function.
JavaScript
We see that by using lodash's foldl function with && and the value true we can create an Anding function.
ECMAScript 2015
Since we live in the future, we'll use Babel to allow us to use ECMAScript 2015. We see again that by using lodash's foldl with && along with the value true we now have an Anding function.
Fin
There you have it the And function using Fold, showing once again that all you need is Fold.
Sunday, August 2, 2015
Bro, Do You Even FizzBuzz?!?
"Do you bite your thumb at us, sir?"
-- Shakespeare, Romeo and Juliet
Act I, Scene I, Line 43
FizzBuzz as an interview kata has been getting a lot of bad press lately. Part of the bad press has been around having to use modulus in the solution. I am not sure how people have been explaining FizzBuzz in interviews, but you do not have to know anything about the mod operator in order to solve the problem.
Here is a solution in Clojure which does not use modulus.
This solution is using cycles and zip. The odds are low of someone knowing how to use cycle and zip but not knowing modulus. The point is that you do not need to know about modulus to do the kata.
In interviews I do, I'll tell the person about modulus if they get stuck. The point of using a kata in an interview is to make sure that person who claims to be a programmer can actually program and that you can work with the person.
Still if the whole modulus thing has you worried, try the Roman Numeral kata.
Here is a solution in C# I did few minutes before an interview on Thursday (pro-tip, always make sure you can do the kata in short amount of time before you ask someone else to do it in an interview).
Again, the goal of the interview kata should be to see if the person can actually program and to see what they are like to work with.
"No, sir, I do not bite my thumb at you, sir. But
I bite my thumb, sir."
-- Shakespeare, Romeo and Juliet
Act I, Scene I, Line 43
FizzBuzz as an interview kata has been getting a lot of bad press lately. Part of the bad press has been around having to use modulus in the solution. I am not sure how people have been explaining FizzBuzz in interviews, but you do not have to know anything about the mod operator in order to solve the problem.
Here is a solution in Clojure which does not use modulus.
This solution is using cycles and zip. The odds are low of someone knowing how to use cycle and zip but not knowing modulus. The point is that you do not need to know about modulus to do the kata.
In interviews I do, I'll tell the person about modulus if they get stuck. The point of using a kata in an interview is to make sure that person who claims to be a programmer can actually program and that you can work with the person.
Still if the whole modulus thing has you worried, try the Roman Numeral kata.
Here is a solution in C# I did few minutes before an interview on Thursday (pro-tip, always make sure you can do the kata in short amount of time before you ask someone else to do it in an interview).
Again, the goal of the interview kata should be to see if the person can actually program and to see what they are like to work with.
"No, sir, I do not bite my thumb at you, sir. But
I bite my thumb, sir."
Sunday, July 26, 2015
On Being Joyful By Contract
"How joyful am I made by this contract!"
-- Shakespeare, Henry VI Part I
Act III, Scene I, Line 144
Act III, Scene I, Line 144
I can think of no book that has had more impact on my career than The Pragmatic Programmer by Dave Thomas and Andy Hunt. One of the tips in The Pragmatic Programmer that I sadly do not find myself using a lot is Design with Contracts.
Design with Contracts
Use contracts to document and verify that code does no more and no less than it claims to do.
-- Dave Thomas and Andrew Hunt, The Pragmatic Programmer
Design with Contracts
Use contracts to document and verify that code does no more and no less than it claims to do.
-- Dave Thomas and Andrew Hunt, The Pragmatic Programmer
Clojure has pre: and post: assertion functions, let us look at an example of the pre: assertion function in a prime tester function.
We can easily see this is not the worlds greatest prime test function, but the point is to look at the pre: assertion function.
We see that in order to call this function we must have the following: 1) the argument used in the call must be a number (defined by number? as instance? Number) and 2) the argument used in the call must not be negative. We see by the tests that if either pre: condition is broken an AssertionError is thrown. Thus allowing us to assume in the body of the function that we have a number and that it is not negative.
If one designs with contracts then one can easily reason about a system since one knows what each part of the system can produce.
Subscribe to:
Posts (Atom)













































