A list comprehension is a syntactic construct available in some programming languages for creating a list based on existing lists. It follows the form of the mathematical set-builder notation (set comprehension) as distinct from the use of map and filter functions.
List all right triangles that have integers for all sides and all sides equal to or smaller than 10 has a perimeter of 24?
Before we continue, please, read the Set Builder Notation article.
As you know, in functional programming we either describing a problem than writing a solution. Let’s describe our problem using Set Builder Notation taking into consideration that side b isn’t larger than the hypothenuse and that side a isn’t larger than side b:
|Output expression or output function. A tuple which contains triangle sides|
|Input set. Builds
|Predicate. Satisfies when coma-separated parts return
Lets do nothing, but translate it to Haskell, using List Comprehension syntax and we will have a ready solution.
BTW, I remember that “equation system solution” exists, but we are doing programming here ;)
Let’s imagine, that we need to create the list of even squares of Integers each of which is less then 100.
Set builder notation solution:
|$0 % 2 == 0`||Predicate|
Now we know all the basics. It’s time to crack the Triangles problem.
Solution should return the
Array of all possible triangles, satysfing the problem conditions. Each triangle is represented with triple (in Haskel - triple is three element tuple)
Let’s build the set of existing triangles with sides lengths
The result contains some extra brackets (which is correct), so we better rewrite it using
Output now is much better. We have the
(Int, Int, Int), or, another word, we built needed set of needed triangles. The only thing we should do is to add the
I made the simple problem complex, wrote some weird code which could be ten times simpler. But functional programming is not just a monad usage. Functional programming is the way, where math and coding go together. It is elegant and beautiful. This article was not a programming use case. It is an attempt to describe different approach to problem solution.