First, let's start with what do we mean by being pythonic.
By googling this term, here is the list of top 3 links:
From those links, I think it's fare to say using list comprehension is a big part of being pythonic. Especially this one is mentioned in all three links.
Let's take one example from second link:
Not so pythonic:
Pythonic:
And this one is brought up in 1st and 3rd links.
Pythonic
Also from second link
Not so pythonic:
Pythonic:
There are also for-in syntax but I believe we've had some sense on what do we refer when we say "pythonic".
So let's see how another language H
looks like, without revealing its full name for now.
Python:
H:
The differences are
| <-
instead of for in
if then else
instead of if else
Python
H:
Difference: the parentheses of tuples are more consistent.
Python:
H:
Difference: the second parameter of range is inclusive.
And TBH, normally it would be written like this:
So what is that language?
The answer is Haskell!
And next, let's have some examples showing Haskell is more pythonic than python in my opinion.
Let's say if we want to do print hello world 5 times:
in Python
in Haskell
Why I think later one is more pythonic? Because it doesn't introduce new syntax, replicateM_
is simply just a function which repeats the given action. Where as in Python code, it's recommended to use for-in for this purpose, in which we need to introduce an unused variable binding _
.
The "unpack" aforementioned can be seen as a special case of Pattern Matching. And pattern matching in Haskell is more versatile.
This means getting list of item only having Right
as the contructor.
Above are two examples, which reveal some aspects of simplicity, for which Haskell can do better. However, this is the very tip of that, and there are many more other interesting concepts in Haskell, which, without using extra syntax, can be used to compose more complex logic I consider Pythonic. For example: async-await is a relatively new syntax in Python. And there aren't many pythonic discussions about it. On the contrary, Haskell can use the same syntax to cover them all.
I think
You might ask, why should I learn a language is not widely used?
My answer to that is, although in the end, you might not use Haskell directly in your job, the knowledge gained from learning it is extremely universal and can be adopted on almost all programming problems.
And since I don't think it should be hard to learn whatsoever, I'll try to write a beginner tutorial which follows the common python beginner curriculum structure.