Monday, May 19, 2014

oh and whats a lambda? ha!



Let’s look at what you need to know to solve something like Fizz Buzz

fizz_buzz = ->(number) do
"#{'Fizz' if (number % 3).zero?}#{'Buzz' if (number % 5).zero?}"

1.upto(100) do |num|
result =
puts(result.empty? ? num : result)


To read this code you’ll need to know that:

This program runs top to bottom.
Expressions return values that can be assigned to variables.
Things can be sent to Standard Out.


Imagine you’re instructing another developer to write this code. What things would they have to understand?

“Assign the result of a lambda expression taking one argument to the variable fizz_buzz. In the lambda, create a string that will interpolate ‘Fizz’ if the argument is divisible by 3, and ‘Buzz’ if the number is divisible by 5. Ensure the string can be ‘FizzBuzz’ for numbers like 15. Then iterate from 1 to 100, calling the lambda with each number. If the result of the call is empty, return the number. Otherwise return the result”.

Implementing this requires you know specific things about the language you’re writing in. Idioms, conventions, methods, objects… To implement this in ruby, you’ll have to know:

How to create a lambda.
How to interpolate strings.
How to get the remainder from a number.
Comparison operators
Statement modifier conditional statements.
Ternary conditional statements.
How to iterate.


To come up with this solution you’ll need a completely different skill. Programmatic thinking. Programmatic thinking is the ability to take a problem and break it down into smaller pieces. To illustrate this, have someone teach a robot how to make a smoothie. Assuming the robot knows only the things you tell it forces you to create very detailed instructions.

For FizzBuzz, the thought process is something like this.

I need something that figures out if it needs to return “Fizz”, “Buzz” or “FizzBuzz”. I could create a class with methods, or just a method, or I can use a lambda. Let’s use a lambda!
I need to print the result out, let’s loop up to 100 and call our lambda!

from Lizard's Ghost

No comments:

Post a comment