Skip to main content

Posts

Showing posts from June, 2014

Code sugar and high-level concepts

Let us multiply all the elements from the set {1, 2, 13} by all the elements of {7, 5}.
Thinking in imperative languages, one may come with two nested loops (or iterators).

Speaking C++
#include <iostream> using namespace std; int main() { int a [] = {1, 2, 13}; int b [] = {7, 5}; for (int i = 0; i < 3; ++i) { for (int j = 0; j < 3; ++j) { cout << a[i] * b[j] << endl; } } return 0; }
In Python I'd rather utilize a list comprehension
>>>  [a * b for a in [1, 2, 13] for b in [7, 5]]
The same goes to the blocks in ruby
> [1, 2, 13].each do |x| [7, 5].each { |y| puts x * y } end
One may find analogous list comprehensions in Haskell. But they aren't cool here.
All you need is applicative functors aka Control.Applicative
(*) <$> [1,2,13] <*> [7,5] Bonus: have you noticed, the C++ code contains a bug which is passed by the compiler? There are only two elements in array b, not three! The pr…