2
$\begingroup$

Some programming languages, apart from functions, have generators (eg. Python's yield). Although generators are introduced in this Python's tutorial on functional programming, I don't think that they can be considered functional programming, because they do have state, and in a vary implicit manner.

Generators are reminiscent of laziness in pure functional languages like Haskell. Apart from laziness, are there other purely functional alternatives for having a construct similar to generators? Do you have any examples?

$\endgroup$
2
$\begingroup$

Functional programming does not have to be pure or stateless. There's no strict rule. Languages that are designed to support first-class functions and higher-order functions can still be considered functional languages. For instance, Standard ML has support for mutable variables but is still considered a functional language.

Also, functional programming can be considered a style of organizing your program rather than a property of a programming language. So, it is possible to use Python in a functional way.

A Python generator can be written in a way so that it is purely functional: e.g., it produces a lazy list/stream and operates in a purely functional way. Internally, generators might be implemented in a way that involves state, but from the outside (from the perspective of code that invokes a generator), I think it is possible to write the generator so it behaves in an observationally pure way (i.e., observationally indistinguishable from pure).

I'm not sure what you mean by "purely functional alternatives for having a construct similar to generators" so I don't know how to answer that part.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.