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++
In Python I'd rather utilize a list comprehension
The same goes to the blocks in ruby
One may find analogous list comprehensions in Haskell. But they aren't cool here.
All you need is applicative functors aka Control.Applicative
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 practical consequence of high-level concepts: cleaner code for less debugging.
Comments
Post a Comment
Please be relevant, helpful and nice.