DEV Community

Functional programming in C++, Python, etc.

Nahiyan Alamgir on November 25, 2018

Let's say I want to print to the screen. In pure functional programming languages like Haskell or Elm, you can simply leave it to the runtime engin...
Collapse
 
rhymes profile image
rhymes

Regarding Python...

I think you already know the answer: you can't...

Collapse
 
nahiyan profile image
Nahiyan Alamgir

You're right, we can't have have 100% pure functional code. The idea is to keep as much of the core pure functional while the rest has to remain imperative.

Collapse
 
lyfolos profile image
Muhammed H. Alkan

Actually, you can. What are the reasons to can't functional in Python?

Collapse
 
rhymes profile image
rhymes

You can do a bit of functional programming: docs.python.org/3.7/howto/function...

It's just that it's not a functional language per se. It was designed as a general purpose, multi paradigm, language.

Thread Thread
 
lyfolos profile image
Muhammed H. Alkan

So basically you're meaning all of the multi paradigm languages has no paradigm, so like Scala is not functional nor object oriented. Sorry but that's a little bit absurd. You just have to obey the rules, nothing else. Functional programming doesn't mean purely functional programming. It's not hard at all functional programming in Python.

Thread Thread
 
rhymes profile image
rhymes

No, I was saying exactly the opposite 😅

You can mix object orientation and functional programming.

Collapse
 
epogrebnyak profile image
Evgeny Pogrebnyak

Check out docs.python.org/3/howto/functional... (as mentioned). For "pure function which prints text on the screen" I think you are stuck, unless you review what is your defintion of fucntional.

If you are to encapsulate your output into IO monad in python you can try github.com/dbrattli/OSlash, but this is just an excercise.

from oslash import put_line, get_line

main = put_line("What is your name?") | (lambda _:
    get_line() | (lambda name:
    put_line("What is your age?") | (lambda _:
    get_line() | (lambda age:
    put_line("Hello " + name + "!") | (lambda _:
    put_line("You are " + age + " years old"))))))

if __name__ == "__main__":
    main()

I thing more fruitful concepts in functional programming are curring, map/filter/reduce and function composition.

Regarding the nice code in gist.github.com/nahiyan/4ea3181b6b... - I think you are just mimicing one behaviour of bind as concat string, while binding can perform different actions on container content. Also there is a difference on class type and an OOP class, as discussed for example here stackoverflow.com/questions/270465....