r/functionalprogramming • u/Imaginary-Deer4185 • 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":
- repeatability
- 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?
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.
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/Inconstant_Moo 9h ago
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:
... but you can also do this and it will figure out what you'd want to be logged and do it for you.
I do have a system which works like exceptions. Basically if you pass any function a value of type
error, it immediately returns theerrorvalue. (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 functionsvalidandunwrapwhich don't do that and are instead allowed to treat errors as normal values. (validreturnstrueif a value isn't anerror;unwrapturns anerrorinto anError, 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::otherValuemakes a copy offoowith 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
fooin 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.