"That many things, having full reference"
-- Shakespeare, Henry V
Act I, Scene II, Line 205
I love to use AutoFixture to setup the the arrange part of my tests. I find that working without worrying about the arrange allows me to focus more on the task at hand. A possible downside of working this way is that AutoFixture is mindlessly setting up all the test data.
Having AutoFixture setup your test data is fine when working with green field classes but when working with legacy code and third party code you getting into cases in which you have circular references. What do I mean? Compare the following:
Case 1:
class A has members with type B
type B has member with type C
type C is a primitive
Case 2:
class X has members with type Y
type Y has member with type Z
type Z has member with type X
In case 1 we have a termination point with type C, AutoFixture can happily go about and create an instance of A and populate all the members in the hierarchy with data.
In case 2 we do not have a termination point, Z has a member of type X which a member of type Y which a member of type Z which goes back to X and so on. Case 2 has a circular reference and AutoFixture is unable to give us back an instance of X without going into an endless loop. Luckily AutoFixture is smart enough to figure out that it is in an endless loop and will error out telling us about the issue.
What do we do if we have a class like X in legacy code or third party code? We'll we can tell AutoFixture that we will have classes like X but that it is fine to just terminate the repeating hierarchy with a null or empty. We use the following to do that:
I normally put this in my TestInitialize for the test class of the offender, but I can see putting in the arrange of a test class if you are mixing old and new. There you have it, a way to use AutoFixture with dirty old classes.
Sunday, December 13, 2015
Sunday, December 6, 2015
AutoFixture for the Win
"What have I kept back?"
-- Shakespeare, Antony and Cleopatra
Act V, Scene II, Line 147.2
Anyone who has paired with me while working in C# knows that I am addicted to AutoFixture. Now I do not try to add it to everything that I am working, but usually it finds its way into whatever I am working on. Why? Simply put, using AutoFixture allows me to focus on the task at hand.
Here is a quick example:
In this example I am implementing the higher order function Map using the higher order function Fold (see my other post if this interested you).
What do you not see in the tests? The setting up of the test data.
Why? It is not important to the task at hand. We do not need it to test the behavior of Map. Map takes a collection and a function and applies the function against every member of the collection producing a new collection. What we want to verify is the applies part, which only requires a collection and a function, the actual members of the collection (and the function) do not matter for this verification.
Staying focus on the task at hand is the power of a test fixture and having someone else implement the test fixture for you is even better. Using AutoFixture with xUnit you really do not need to think about setting up test data at all and that is good thing.
-- Shakespeare, Antony and Cleopatra
Act V, Scene II, Line 147.2
Anyone who has paired with me while working in C# knows that I am addicted to AutoFixture. Now I do not try to add it to everything that I am working, but usually it finds its way into whatever I am working on. Why? Simply put, using AutoFixture allows me to focus on the task at hand.
Here is a quick example:
In this example I am implementing the higher order function Map using the higher order function Fold (see my other post if this interested you).
What do you not see in the tests? The setting up of the test data.
Why? It is not important to the task at hand. We do not need it to test the behavior of Map. Map takes a collection and a function and applies the function against every member of the collection producing a new collection. What we want to verify is the applies part, which only requires a collection and a function, the actual members of the collection (and the function) do not matter for this verification.
Staying focus on the task at hand is the power of a test fixture and having someone else implement the test fixture for you is even better. Using AutoFixture with xUnit you really do not need to think about setting up test data at all and that is good thing.
Labels:
autofixture,
C#,
mapping,
xunit
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 20, 2015
The Cloud-Capped Towers OR AutoFixture
"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,
Leave not a rack behind. We are such stuff"
-- Shakespeare, The Tempest
Act IV, Scene I, Lines 152 -156
In my day-to-day work I do a lot of .Net programming. It seem at some point in each of the applications I am either enhancing or creating I ended including Mark Seemann's AutoFixture (if it is not already in use). AutoFixture is an easy way to create a fixture object. A fixture object is an object which centralizes your helper methods in your test code, like methods which create your system under test and help generate test data.
Fixture objects are great and I often find myself wanting one in my day-to-day work, but I am lazy. Since I am lazy I do not want to go to all the trouble of creating my own fixture object, to quote Homer Simpson, "Can't someone else do it". Luckily in the .Net realm someone already has, Mark Seemann. AutoFixture lets you get the best of all worlds, you get a fixture object and you do not have to write the framework around it! (working with it for a few years now, I can say it is well thought out and not a big hair ball, see also Simple Made Easy for the full reference)
How about some examples? (taken from the AutoFixture cheat sheet and rewritten using xUnit)
We see in the above lots of wonderful things.
Another framework I use a lot in my day-to-day .Net programming is Moq. Guess what, AutoFixture can be uses as an auto-mocking container with Moq (and it has plugins for other mocking frameworks too).
Yet another example. (using MS Test taken from an overview of AutoFixture I did at work recently)
We see in this example that we had a simple class called Echo which got top hatted into having logging and a backup added to it. The interactions with the logger and back-upper need to be tested, luckily we can tell the fixture object that we would like to get spy objects for the logger and back-upper. These spies from AutoFixture are Moq mocks which allows us to verify that the behaviors we want.
By using AutoFixture and Moq we can meet all the "needs" of Top Hats everywhere.
(The term Top Hats comes from Uncle Bob's Clean Coder series episode 7, in which there is a scene with an Architect talking about choosing an IDE and Database for a project hence the term Top Hat and top hatting to describe this type of "architecture".)
I find that AutoFixture allows me to simplify my test code (simple as discussed in Simple Made Easy) and allows me to stay focus on what I am actually trying to test.
The solemn temples, the great globe itself,
Yea, all which it inherit, shall dissolve,
And, like this insubstantial pageant faded,
Leave not a rack behind. We are such stuff"
-- Shakespeare, The Tempest
Act IV, Scene I, Lines 152 -156
In my day-to-day work I do a lot of .Net programming. It seem at some point in each of the applications I am either enhancing or creating I ended including Mark Seemann's AutoFixture (if it is not already in use). AutoFixture is an easy way to create a fixture object. A fixture object is an object which centralizes your helper methods in your test code, like methods which create your system under test and help generate test data.
Fixture objects are great and I often find myself wanting one in my day-to-day work, but I am lazy. Since I am lazy I do not want to go to all the trouble of creating my own fixture object, to quote Homer Simpson, "Can't someone else do it". Luckily in the .Net realm someone already has, Mark Seemann. AutoFixture lets you get the best of all worlds, you get a fixture object and you do not have to write the framework around it! (working with it for a few years now, I can say it is well thought out and not a big hair ball, see also Simple Made Easy for the full reference)
How about some examples? (taken from the AutoFixture cheat sheet and rewritten using xUnit)
We see in the above lots of wonderful things.
- We can walk up to the fixture object and ask it for some test data.
- We can use the AutoData attribute and ask for test data.
- We can register implementation for abstract types.
- We can create collections of test data.
- We can build specific test data saying what attributes we care about and letting the fixture object set up the rest.
- We can even have a do method to allow for modification outside of the object we are having the fixture object create (this is not good design but sometimes it is needed).
Another framework I use a lot in my day-to-day .Net programming is Moq. Guess what, AutoFixture can be uses as an auto-mocking container with Moq (and it has plugins for other mocking frameworks too).
Yet another example. (using MS Test taken from an overview of AutoFixture I did at work recently)
We see in this example that we had a simple class called Echo which got top hatted into having logging and a backup added to it. The interactions with the logger and back-upper need to be tested, luckily we can tell the fixture object that we would like to get spy objects for the logger and back-upper. These spies from AutoFixture are Moq mocks which allows us to verify that the behaviors we want.
By using AutoFixture and Moq we can meet all the "needs" of Top Hats everywhere.
(The term Top Hats comes from Uncle Bob's Clean Coder series episode 7, in which there is a scene with an Architect talking about choosing an IDE and Database for a project hence the term Top Hat and top hatting to describe this type of "architecture".)
I find that AutoFixture allows me to simplify my test code (simple as discussed in Simple Made Easy) and allows me to stay focus on what I am actually trying to test.
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."
Subscribe to:
Posts (Atom)