r/functionalprogramming • • 8d 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?

8 Upvotes

32 comments sorted by

12

u/pthierry 8d 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.

1

u/Imaginary-Deer4185 8d 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 ... 😄

6

u/kbielefe 8d 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.

0

u/Imaginary-Deer4185 8d 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.

2

u/garagedragon 7d ago

You don't need any extra threads in that example. The critical information (and which isn't provided in the syntax) is whether mutations to the value of a inside f can be seen by f's caller. If they can't, all sorts of things simplify, including that you don't even strictly need to care whether a is passed by value or by reference - the compiler could even transparently pick whichever is most efficient, assuming you don't have any ABI restrictions or the like. If they can be seen, and there's no specific syntax that distinguishes references that can mutate from ones that can't, (e.g. Rust would spell that example f(&mut a)) it becomes much harder to track what values have been changed by callee functions and which can be assumed to stay the same. It also means that two such calls have an implicit data dependency, because the second call must see any updates the first call carries out. Immutable calls do not create such an ordering.

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.

The way I think of it is that "purely functional" languages like Haskell are functional as in mathematical functions - you're working in an abstract Platonic realm where the only dependencies are data-dependencies, i.e. you need to evaluate one expression first because a second expression needs to do something more to its value. The temporal order those expressions are evaluated in is both irrelevant and impossible for anything to observe or depend on because there's no sense that these things need explicitly computed yet, they just are.

Various Haskell constructs exist basically to re-construct notions like temporal dependencies and side effects (whose relative order matters) so that haskell code can make sense to execute on a physical computer that has to interact with a temporal world rather than the purely atemporal world of pure mathematical expressions that just timelessly exist.

5

u/AppropriateTeach169 8d ago edited 8d 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 ... 😄

-1

u/Imaginary-Deer4185 8d 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.

4

u/AppropriateTeach169 8d 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.

2

u/garagedragon 7d ago

Yeah, referential transparency basically leads to all the rest. If it can't possibly vary (or cause anything else to vary) based on when you look at it, there's no need to look at it at all if you don't need the value.

0

u/Imaginary-Deer4185 7d ago edited 7d 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!

3

u/adambard 8d 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.

2

u/Imaginary-Deer4185 7d 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.

2

u/pthierry 6d ago

FP benefits may be dependent on immutable data or the absence of side effects, or both (which means pure functions).

Determinism and the following benefits of FP need both.

  1. It's easier to reason about the code, because you don't need to fully understand the full call tree of the function f() to understand f().

Note that it's true for humans, but it also means you need less in the context window of an LLM, and formal methods will be simpler to apply.

Spooky action at a distance is a huge PITA in my opinion, removing it feels invaluable.

2) You can parallelize code execution without changing anything in the code and it's guaranteed to produce the same result as a sequential execution.

This has the distinct advantage that the barrier to trying parallelization is far lower.

3) You can run code concurrently without changing its behavior. Obviously, the code that uses concurrency will not be a pure function itself, almost every way to do concurrency is non deterministic, but if that non deterministic code only calls pure functions concurrently, those will have a deterministic behavior in terms of return values (not in terms of timing, which is the principal source of non determinism here).

4) Pure functions' results can be cached reliably, which opens up a ton of opportunity for performance optimization, starting with memoization, but up to distributed caching (if you add the guarantee that only identical code use a common cache, of course).

5) Pure functions make lots of optimizations possible. They don't need write barriers anywhere, and the compiler can transform several calls into a single one, sometimes even execute the call at compile time and transform those calls into constants. Optimization around unboxing like the wrapper/worker are not possible without pure functions, I think.

6) Imperative code can be expressed by data structures that can be later interpreted in several ways. This opens up possibilities like algebraic effects or software transactional memory, which cannot be done reliably if side effects are present.

Languages like Haskell and Elm don't include impure functions at all. They use this technique to express code with side effects (the IO monad in Haskell and the commands in the result of the update function in Elm).

2

u/pthierry 6d ago

If f(x) can mutate x, how could you guarantee that [f(x), f(x), f(x)] will always contain three equal values‽

If it doesn't, it means that f is not deterministic and you lose every benefit of FP rooted in determinism.

2

u/Imaginary-Deer4185 6d ago

This is true. It doesn't mean losing all determinism, though. The guarantee of same result for same input stands.

2

u/pthierry 6d ago

What are talking about? I'm calling the function three times with the same input and I get there different results!

2

u/Imaginary-Deer4185 6d ago

If f(x) modifies the x, then clearly the input is not the same. The guarantee of the same value for the same input stands.

2

u/pthierry 5d ago

But that's the point if immutable data!

Now I need to fully understand every function that could touch any variable in the call tree of my code to know if several calls of one function with the same variables as arguments will actually be calls with the same values.

If that's my mental burden to benefit from determinism, they I don't benefit from determinism.

Also, as always, that means that even if I managed to assert that some calls are identical, I now need to track every single change in functions appearing anywhere in the call tree of my code to know that my assumptions don't get invalidated.

2

u/Imaginary-Deer4185 5d ago

You do have a point. My concept takes away that guarantee, and I acknowledge now the mental burden you describe. I never thought of it that way, instead thinking that each sub-function that we call directly from a (pure) body of code, have well-defined meanings, which we relate to as programmers. But two years later, those exact meanings get blurred.

Yes, in order to maintain code written by others or some time ago, one needs to understand the working of the code, but I see that eliminating changes to input, means less cognitive overhead, with more to spare for the other "data path", which is the (partial) results coming from the functions of the call tree.

Furthermore, and strictly speaking, modifying input data will easily mean losing information, which reduces the flexibility for when deep-stack functions need to react to original content. It is one thing having to pass additional structures down the call path to sub-functions, it is another altogether having thrown away certain data by mutation.

3

u/Inconstant_Moo 7d 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.

2

u/SuspiciousDepth5924 8d ago

You do you and all that, but unless you have some really compelling reason for doing so I highly recommend avoiding the "pass by pointer and mutate"-pattern because it ends up breaking referential transparency, it also means concurrency and parallelism becomes really annoying because you have to start doing the whole mutex/semaphore thing.

Usually there's not much performance gain either because the objects with shared references generally have to be placed on the heap.

4

u/Inconstant_Moo 7d 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.

2

u/Imaginary-Deer4185 7d ago edited 7d 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.

2

u/Inconstant_Moo 7d 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.

3

u/unqualified_redditor 6d ago

I've never coded in an FP language, but have some questions.

I think you should try using FP languages before trying to formulate theories about them.

2

u/Imaginary-Deer4185 6d ago

I am formulating a theory for an FP-adjacent or FP inspired language, based on two central points, or guarantees: determinism and testability. My list of things I don't want to care about, is what, as I see it, separates it from FP languages.

In my mind, how a function arrives at its value, in terms of coding style, and whether the input value is also the return value, does not change the concept of determinism, as long as the function does not ingest dynamic data from the outside (databases, system time etc).

The point of this concept is dispensing with supposedly costly operations that follow from immutable data, as well as recursion, and also being able to use imperative style code, which is something much more available to most people, than map and fold and no local variables etc.

Others have explained that if function f(x) modifies x, then calling it again with the "x" variable, delivers a separate result, and consider that troublesome. In my mind, unless one writes really long functions, it is a theoretical issue.

I am however not suggesting my theorized language have all the properties of FP languages. In particular I mentioned that parallelism is out of the question, if allowing stateful objects. The point is and was to highlight what my proposed language would lose, compared to "real" FP.

My question was open ended, asking if these two guarantees were of proper value for such a language to be created. As I said, I am practically oriented; I write code, and want to do so with the least amount of pain.

7

u/Justneedtacos 8d 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/

2

u/AppropriateTeach169 8d ago

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

3

u/Justneedtacos 7d ago

Microsoft supports it

2

u/catbrane 8d ago

I'd suggest:

  • Passing data as pointers, for modification inside functions is okay and preferred

The main wonderful thing that FP gets right is immutability. It makes reasoning about code so much simpler since you no longer need to consider the order of operations (the execution history of your program). The value of a function depends on the value of the parameters and nothing else. It will never change.

I'd adjust your rules to be:

  • all objects and structs are immutable
  • exception: you can assign fields during object / struct construction
  • you never modify objects, you only create new objects
  • any number of devious tricks to share state between immutable objects and speed up construction are a-ok
  • reference counting is extremely useful!
  • now you can trivially evaluate in parallel, cache results, all that

Over this core functional layer, have a non-functional system for interactivity. Interactive systems are a state that evolves over time, so imperative designs are a more natural fit.

This is more or less the approach that languages like Haskell take. The core language is purely functional, then they spread a thin layer of monads over that for the very top levels.

My spare time project works like this. It's a purely functional image processing library written in C/C++, with bindings for imperative languages. The functional core means it can thread and cache very aggressively, and lazy evaluation makes it light on memory.

https://www.libvips.org/API/current/how-it-works.html

2

u/dihamilton 6d ago

I found Grokking Simplicity a good book on practical functional principles. Put as much logic into pure functions as you can, functions that return the same result for the same input but also are guaranteed not to change the state of the world. It might seem cumbersome at first but it really is a powerful way to create testable, composable code.

2

u/yawaramin 5d ago

Have you written anything in an FP language or framework? I recommend trying out Haskell (for a pure FP experience) and OCaml (for a mixed-FP/imperative style) to help clarify your thoughts into concrete questions.