r/functionalprogramming • • 21h ago

Question A "practical" approach to FP?

A bit long. Sorry.

I've never coded in an FP language, but have some questions. By "practical" I am trying to bridge the gap between imperative and functional programming, perhaps naively.

To me, as a long time software developer, the major issue using languages like Java, Python and C, is predictability and testing.

To this end, I've pondered the functional approach, but only with regards to two potential "promises":

  1. repeatability
  2. testability

My proposal is founded on "imperative shell, functional core", in the sense that the functional part is a transformation engine, and the shell is "instructed" by the functional code as to what data to obtain in order to continue the transform of request to response. This could be waiting for a user, loading from a database, doing network protocols, etc.

The "instructions" to the shell should be a simple list of do this, do that, and might contain concepts such as timers and timeouts, of which the functional core has no knowledge, other than what is passed in as parameters.

By creating functions that generate results solely based on parameters, we have repeatability. No outside influence is allowed, no filesystem access, no network, no system resources.

For a given input, functions always produce the same output. That is the first promise.

The second, testability, comes from same fact, that results follow from parameters. In tradititional imperative code, logic is intertwined with fetching data from the outside world, upon which we apply logic, and which results in wildly differing output.

With all input to a function coming in the form of parameter data, of which we can manufacture many sets, we can test a function both for bugs, as well as do regression testas following code changes.

Note the points that I do NOT concern myself with:

- I don't care in what style functions are coded
- Local variables are okay, as is imperative loops
- Passing data as pointers, for modification inside functions is okay and preferred
- There is nothing wrong with using objects, as long as those don't have persistent state (associated with the class or elsewhere)
- Exceptions are okay
- I see no point in limiting logging; as long as the logging interface is strictly output, it will not affect logic

From this follows one limitation, that code can not be parallel, since this would mean multiple live references to shared data, which may shift due to timing and logic at other locations.

Are my two promises valuable enough that implementing such a system would make sense?

5 Upvotes

21 comments sorted by

8

u/pthierry 18h ago

I just made a presentation of FP in a local software craftsmanship meetup, and the first benefit of FP I explained was determinism, saying it has very direct and practical implications on deployment and testability.

The thing is, if you dig just a little bit into why FP gives you determinism, it comes down to pure functions. And it's easy to include things in your functions that you may not realize will make them impure.

If you have mutable data passed to your functions, you immediately lose any possibility of determinism. That's why even the functional languages that permit side effects still work exclusively with immutable data structures (e.g. Closure, Elixir or Ocaml.

Logging might be okay but I'd avoid it except for debugging. Exceptions for things like division by zero are mostly okay, but don't use them for business logic errors.

It's a perfectly valid approach to use FP techniques in an imperative language, some of them have long lived libraries to make it easier, like Guava in Java or Immer in C++, and some even provide support for FP from the get go.

But to learn FP, I'd recommend using a functional language, and the constraint of a language that excludes side effects might actually make it easier to dive into FP. Elm is a wonderful language to try FP.

•

u/Imaginary-Deer4185 15h ago

"If you have mutable data passed to your functions, you immediately lose any possibility of determinism"

I think it depends on who is doing the mutation and the scope.

If a function receives an object with inner state, and mutates it, before passing it on to other functions, with the intent of them modifying it as well, and there is no hidden global state associated with the object (such as class fields), then what makes this lose determinism?

This is what I don't understand about FP, it sounds like an anxiety that mutating local variables may somehow "get out" into the environment, like some virus ... 😄

•

u/kbielefe 14h ago

Say you have code like:

a = 42
f(a)
-- What is the value of a here?

With immutability, you know a hasn't changed, without having to understand what f does with it, or what the functions f calls do with it, or the functions they call, all the way down the stack. Or what other functions in other threads are doing with it.

Without realizing it, imperative programmers spend a tremendous amount of mental effort on tracking side effects.

•

u/Imaginary-Deer4185 12h ago

I explicitly stated that my model does not include support for threads within the pure function hierarchy. Another thing it potentially loses, is formal verification, if that is a thing in actual project work.

A third may be lazy evaluation and the out-of-order processing that may follow.

For those cases, having called functions modify the stuff you send to them, surely messes things up. My "practical" point of view is imperative code inside functions, but removing the traditional interwoven calls to databases and system resources, that mess up predictability.

I have a hard time seeing lazy evaluation and out-of-order processing as a core tenant of functional programming, but I am probably wrong on this.

•

u/AppropriateTeach169 14h ago edited 12h ago

It's about systematic enforcement rather than conventional compliance to a style. It is about forcing you to not be able to mutate in the language. Making it inexpressible. Do you understand what the distinction I'm drawing?

The whole mess you described is unfortunately made useless by the prevalance of destructive reflection. Just make it immutable as your only rule with no exception especially in your particular case. When you really need mutation, you won't be typing comments such as the one you posted. Just to paste it here in case you delete the comment:

"If you have mutable data passed to your functions, you immediately lose any possibility of determinism"

I think it depends on who is doing the mutation and the scope.

If a function receives an object with inner state, and mutates it, before passing it on to other functions, with the intent of them modifying it as well, and there is no hidden global state associated with the object (such as class fields), then what makes this lose determinism?

This is what I don't understand about FP, it sounds like an anxiety that mutating local variables may somehow "get out" into the environment, like some virus ... 😄

•

u/Imaginary-Deer4185 7h ago edited 6h ago

The whole mess you described is unfortunately made useless by the prevalance of destructive reflection. Just make it immutable as your only rule with no exception especially in your particular case. When you really need mutation, you won't be typing comments such as the one you posted. Just to paste it here in case you delete the comment:

Wow!

•

u/Imaginary-Deer4185 12h ago

I understand the what but not the why, unless lazy evaluation and out-of-order execution is one (of many) defining characteristics for FP.

I guess my thoughts on marrying imperative code into "pure" functions, with the promises of repeatability and testability, is far from sufficient to call it an FP language.

And I respect that, because names and terms matter.

•

u/AppropriateTeach169 11h ago

It is not that lazy evaluation and out-of-order execution is one of the defining characteristics for FP. It is that referential transparency and order-of-evaluation are concerns in FP. Notice the reframe. Imperative code doesn't matter if it's not needed. It can be written well where it's needed without the burden of pegion-holing.

•

u/adambard 11h ago

This is what I don't understand about FP, it sounds like an anxiety that mutating local variables may somehow "get out" into the environment, like some virus ... 😄

That's kind of the problem in a nutshell.  It's not that you can't write FP-style code in a library with mutable collection types. It's that you don't get any of the guarantees that FP languages and, especially, immutable collection types give you in this environment. You either have to trust that every function leaves its inputs alone, or verify them yourself (which uses up valuable brain space that could be otherwise spent on your actual business logic).

If you're coding alone , this is no problem, you can just not do it and trust yourself. The problem comes when the program involves other people (or, is old and forgotten enough that you can no longer trust yourself!)

I've always been of the opinion that immutable collections were the main benefit here, and FP styles emerge to make them easier to work with.

There also a performance penalty you pay if your code is copying whole collections to avoid mutations, which immutable implementations can ameliorate in various ways, but that's a different subject.

•

u/Imaginary-Deer4185 7h ago

My point of view is as someone who enjoys creating interpreters, and now examining the possibility of marrying pure functions with imperative code.

Because, the biggest hurdles to software maintenance in traditional imperative languages (Python, C, Java), is that code deep down the call stack accesses external resources, fetches dynamic data, and makes decisions based on those. This makes it hard to test stuff, not only from the variability of the data, but also having to set up test environments with databases and stuff, to satisfy the needs of the application.

I don't understand the need for callers to check if the function called has not changed the inputs, since that is a frequent way of producing the desired output, rearranging the input. Using imperative code, there is also no doubt about order of execution, when parallelism is taken out of the picture. Also, in my experience, functions have names according to functionality, with parameters to match. If I want to create a function that rearranges a list, in a 100% predictable way, what need do I have for working on a copy?

But for completeness, what other guarantees do FP languages provide, in a practical sense, besides predictability (and testability)?

I am fully aware that I am ignorant of what the FP term is taken to mean, in its fullest, and it is not my intent to insult or offend anyone. As I wrote elsewhere, it probably isn't acceptable thinking of my language concept in FP terms. At least one contributer seems to have taken great enough offense to posting my "madness", to quote me, in case I try to "delete the evidence". Hillarious and a bit sad.

•

u/Inconstant_Moo 9h ago

You're confusing mutating local variables with mutating values. The first one is just a source of footguns, the second is the one that can "get out".

And if your mutable value can ever be passed to anything that can do input from the user or the file system or the database, then you do lose determinism.

4

u/Justneedtacos 16h ago

To follow up with the excellent advice from u/pthierry :

I’d add F# to his list. It’s similar to Ocaml but has better runtime support on major clouds, access to a rich ecosystem in dotnet, a Hindley-Milner type system like Elm, a web framework called Elmish that is like Elm, and computation expression syntax to help ease you into monads and applicatives.

I found Mark Seemann’s writings, presentations, and pluralsight courses to be some excellent practical and concrete introductions to leveraging the advantages of functional programming. Example:
https://blog.ploeh.dk/2016/03/18/functional-architecture-is-ports-and-adapters/

•

u/AppropriateTeach169 14h ago

How did F# gain support when I don't see it used much

•

u/Justneedtacos 9h ago

Microsoft supports it

•

u/Inconstant_Moo 9h ago

My proposal is founded on "imperative shell, functional core", in the sense that the functional part is a transformation engine, and the shell is "instructed" by the functional code as to what data to obtain in order to continue the transform of request to response. This could be waiting for a user, loading from a database, doing network protocols, etc.

That would be functional shell/imperative core, not functional core/imperative shell. You don't have repeatability if the shell is fetching data from the user, a database, a web service. That's an outside influence.

In FC/IS, the commands that move data about are at the root of the call tree, and they ask the pure functions to supply their business logic. For example, here's a tiny text-based adventure game in my language (Pipefish). The imperative bit loads the resources, asks the player "What next?" and updates the game state, while the functional bit calculates what the new game state should be.

https://github.com/pf-lang/pipefish/blob/main/examples/adventure/adv.pf

As for the rest of your shopping list, I have things that look and feel a lot like imperative loops, but which are in fact functional loops in which no variables are mutated. You can see one in the last function of the example above. I do allow logging in my pure functions and make it very easy. Not only can you do something like this:

parity(i int) :    \\ Called `parity` with `i` = |i|.
    i mod 2 == 0 : \\ Tested if `i` is even.
        "even"     \\ Returned `"even"`.
    else :         \\ Took the `else` branch.
        "odd"      \\ Returned `"odd"`.

... but you can also do this and it will figure out what you'd want to be logged and do it for you.

parity(i int) :    \\
    i mod 2 == 0 : \\
        "even"     \\
    else :         \\
        "odd"      \\

I do have a system which works like exceptions. Basically if you pass any function a value of type error, it immediately returns the error value. (Without you having to make this clear in the type system, it just happens.) This means that errors force their way up the stack. To do error handling, there are two functions valid and unwrap which don't do that and are instead allowed to treat errors as normal values. (valid returns true if a value isn't an error; unwrap turns an error into an Error, a normal struct which contains all the relevant data).

Instead of having objects containing mutable state, I make it easy to copy-and-mutate structs. foo with key::value, otherKey::otherValue makes a copy of foo with the two fields updated to the two new values.

Immutability is more powerful than you think, I can see in some of your other comments that you're puzzled as to why people want it. Well, for example, in Pipefish if you have a username and password for another Pipefish service, you can use it syntactically and semantically as though it was a library --- and vice-versa, you can point one of your libraries at the internet and call it a microservice.

But the only reason this works is immutability, otherwise what happens when the client service wants to say "Hey, remember that mutable value you passed me a week ago? I just mutated it ... oh, wait, you're offline? Welp, I'm off to tell the other half-dozen services I'm sharing that value with ..." and the whole thing goes crazy.


Pipefish is broadly what you want --- "a practical approach to FP" --- in that it prioritizes DX over the powerful abstractions offered by other functional languages, and has been designed to be particularly good for quickly hacking out enterprise software, CRUD apps and middleware.

But your idea of what's "practical" involves giving up too much of what makes FP so attractive in the first place. Of course local variables should be declared and immutable and lazily evaluated rather than assigned and mutable and eagerly evaluated, because this separates two things that should never, ever, ever have gotten mixed up --- giving names to our concepts, and flow of control. Because of this mix-up, every single time I'm trying to read imperative code, the meaning and purpose of a variable foo in any line in a function might depend on the path the function takes to arrive at that line, and I always have to consider that possibility. In Pipefish, I never have to think about that possibility while writing code, and a source of permanent mental friction is removed.

•

u/Imaginary-Deer4185 6h ago edited 6h ago

You're the first to explain the point of immutable local variables properly, and the mental friction of having to relate to what the code does, to follow the value of variables. And that is a valid point. Thank you for that.

I got the "imperative shell, functional core" term from pipefish, which I have been reading a bit about before making the OP of this thread. You say that my shell is the functional part, and the core the imperative. Is that because I argue for an imperative programming style, but with the restriction of not allowing access to the environment, other than as asking the shell to do it?

I guess all the code of the suggested design is imperative, but with the core delivering the two guarantees (predictable, testable). I should perhaps not have asked here at all, and instead directed it to the more general ProgrammingLanguages sub.

•

u/Inconstant_Moo 6h ago

Perhaps reading it again I misunderstood what you meant by "the shell is "instructed" by the functional code as to what data to obtain". If this is done by the shell calling the functions, that's fine --- it read at first like you were saying the functions called the shell, in which case it's not the shell.