by yodsanklai · 2y ago · 0 comments
I'm always surprised reading comments on these topics, people saying they don't grasp FP. But don't we use higher-order functions, closures, combinators all the time in most mainstream languages? How hard can it be to learn OCaml or Clojure for someone who use closures all over the place in JS?
Monads have a steeper learning curve, but besides Haskell, they aren't that pervasive. And there are constructs with similar flavor in mainstream languages too (result types in Rust...)
I recently gave a talk to some colleagues about that, which was divided into two parts: Practical functional programming patterns we can use today in our codebases (we use mainly C++, Python) and a more abstract part about pure functional programming.
The first part basically boils down to using functions as first class "objects", while the point of the second part was, that there can't be implicit state in pure functional language. The consequence of that is, that there is no strict order of execution, which is in direct contrast to imperative programming, which is all about list of statements, that are executed one after another.
I presented small code examples in Haskell and showed corresponding execution graphs to emphasise, that the compiler can easily optimise the execution order.
I like that POV, because it clearly distinguishes imperative from functional programming. Starting from there, it's also easy to understand the motivation behind monads or elaborate on architectural patterns like " functional core, imperatively shell".
E.g. the following in JS will always print the confirm message. But in a lazy language like Haskell, as the x parameter is never used, it'll never be printed.
(function(x) { return "bar"; })(confirm("foo"));
This can help with implementing things like infinite streams (e.g. iterate[0] in Haskell), which may be a pleasant patterns to solve some problems sometimes. On this example alone, I wouldn't qualify it as highly relevant for day-to-day work, but there may be more interesting use cases I'm not familiar with (I'd guess there might be interesting side-effects in concurrent settings).[0]: https://hackage.haskell.org/package/base-4.20.0.1/docs/Prelu...
$ echo "hello world"
hello world
I can do: $ "hello world"
hello world
Is this an indication that it is expression oriented? (just checking that I've understood the phrase).`"hello world"` is an expression with the literal string value "hello world"; your REPL probably prints out that expression's value once it is evaluated for convenience.
FWIW I'm not actually familiar with nushell and am speaking fairly generally about statements vs. expressions.
Essentially, statements have no value (or return no value). Expressions have a value.
For example, while I can do FP in Rust, I would not really call Rust a FP language. It does have some features that make doing FP possible, but a lot of the code I see (and write) is a mix of imperative and FP.
But if I'm writing Scala, I'm going to be mostly writing FP code, and the language helps me there. Recent versions of Java make it easier to write FP code if you so choose, though you'll still see a lot of people write more imperative code in Java.
(I think if Rust had Scala's for-comprehensions, I'd write more FP-ish Rust. I know there are crates that emulate them, but they're not the most ergonomic, and I don't want to write what ends up being unidiomatic Rust code.)
I think if Rust had Scala's for-comprehensions, it would be a strictly worse language than it is now. FP langs' do- and for-comprehensions are highly unergonomic, not least due to all the ways it could be overloaded. Haskell has tons of extensions, Scala's is basically desugaring to flatMap calls. This has a lot of abuses in the wild, and with how it depends on implicits causes practical problems when you write that code.
Scala's new wave of direct syntax and general direction from Monads to algebraic effects is more sane in how it presents compiler messages, and opens ways to have better performance.
We just don’t call them monads.
Here is a translation of a modification of the example given in [1]:
const promise1 = Promise.resolve(123);
promise1.then(v => v * 2).then((value) => {
console.log(value);
// Expected output: 246
});
into Haskell: ghci> let promise1 :: IO Int = return 123
ghci> promise1 >>= (return . (* 2)) >>= print
246
One key discrepancy worth pointing out is that in the `Promise.then()` API of JavaScript, the function provided to `then` (e.g. `v => v * 2` above) is implicitly composed with a call to `::resolve` in order to turn that function's pure return value, the `Number` 246, into a Promise resolving into the `Number` 246; in Haskell, this operation must be made explicit (hence the composed function `return . (* 2)` passed to the first application of (>>=) or `bind`).You could say that the instance method `Promise.then()` expects an argument of type (a -> b), with the return value of type `b` being implicitly and automatically wrapped into a Monad `m b`, whereas Haskell's bind expects an argument of type (a -> m b) on that operator's right-hand side, with the return value explicitly wrapped into a Monad `m b` by the provided function argument itself.
[0] https://wiki.haskell.org/Monad
[1] https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...
So in essence Promise.then() is like Array.map() while bind is like Array.flatMap()
Edit: It seems you are correct, you can indeed return a promise in the callback and it compose correctly. But in your example the callback does not return a promise and is therefore not an example of monadic bind.
We don’t really use them in mainstream languages. They exist as idioms for shallow application, but one doesn’t go full-on combinators in javascript, for at least performance reasons. What we do in mainstream is as FP as walking stairs compared to rope climbing.
That said I think deep FP makes no sense and only entertains bored intellectuals by being a subspecies of code golf.
- understanding paradigms of state handling enables you to make conscious choices about what to aim for, how to design your data model, etc
- learning the benefits of having all data as values, except at the edges of the system (instead of object refs encompassing mutable state and/or IO handles)
- eg the resulting ability to reason about your system in a principled way (this can still be hard to mentally reach, even given all the ingredients, if you're very used to the "poking the mystery ball" way of relating to your app)
- how it comes together so you can just test a subset of your code at your REPL, being able to paste the input datastructure there (because it's just values, not active objects) without having your app framework up and running in a stateful context in browser or server environment.
Another strength of FP is about paralell programming. The bottleneck of parallelizing code by using multiple threads is concurrency bugs which come from mutable data. Immutable data and referential transparency is close to a silver bullet for this. (But JS programmers aren't as likely to appreciate this since JS is nearly always single-threaded)
If you go to https://en.wikipedia.org/wiki/Functional_programming right now you will see "functional programming is a programming paradigm where programs are constructed by applying and composing functions" which is a bit of a ... it is quite hard to program without doing that. Even SQL is basically applying and composing functions. There are languages that are branded together because they have similar communities or techniques, but the brand isn't describing something beyond people thinking that things belong in a basket together.
It may be that different people mean different things when they talk about FP. I come from the Haskell corner and from my point of view that's a completely insane claim, at least when it comes to pure FP.
[ ] Are you writing a procedure that just processes its arguments into a return value? [ ] Does the procedure also operate on a non-static context? [ ] Does the procedure generate additional side effects?
If you answer yes|no|no, you are programming purely functionally.
The formal litmus test is the question of whether your procedure actually fulfills the definition of a mathematical function with regard to the relationship between the arguments and the return value. If it also does not generate any side effects, it is a purely functional procedure!
Then you can apply the principles of mathematical composition of functions to the construction of programs. Purely functional languages force you to program this way by default and to use special constructs for everything that has to do with side effects: IO monad, algebraic effects, The Elm Architecture.
How are you supposed to program like this? This is where (in addition to the concepts mentioned above) the higher-order functions that everyone knows come into play: map, fold, filter, flatMap, ... If you only know these and their use in impure languages, as if this were nothing formally thought through, but just a programming style for hipsters, then I can understand how the impression arises that there are no precise definitions here.
In practice, the concepts are often very distorted or not understood at all. For many programmers, OOP mainly seems to mean that you get the drop-down list with completions in Rider when you press “.”.
main = do
v <- newIORef 0
let procedure = do
n <- readIORef v
print n
modifyIORef v (+ 1)
...
and have a look at the conditions you laid out* Are you writing a procedure that just processes its arguments into a return value?
No, it has no arguments and its return value is just (), but it does more besides.
* Does the procedure also operate on a non-static context? Yes, it operates v
* Does the procedure generate additional side effects? Yes, it prints to the terminal.
So I have answered no | yes | yes, the exact opposite of what I should have to be classed as doing pure functional programming.You might say "Ah, but the return value of `procedure` is not (), it's IO ()", but I don't see that that changes anything. I can write my entire program in IO if I want, in a way that's hard to distinguish from having written it in, say, Python. Is that not pure functional programming, despite the fact that it's being carried out in Haskell? Then you might say "Ah, but the difference is that you could have written your program purely, without IO". But again I fail to see how that differs from Python. I can write programs that don't do any IO in Python too.
So what is it that makes Haskell a pure functional language and Python not?
My response to all this is that the notion of "pure" is very unhelpful and the correct way to describe this property that Haskell has is "referential transparency", that is
let x = rhs in ... x ... x ...
has the same result as ... rhs ... rhs ...
regardless of how many times (or zero) x occurs.> but I don't see that that changes anything
It changes everything, but I can't explain it any better than I did above.
> So what is it that makes Haskell a pure functional language and Python not?
If you give me a Haskell procedure `f1 :: Int -> Int` without showing me the content, I still know that it is referentially transparent and pure. If f1 evaluates x to y once, I know that it ALWAYS evaluates x to y. If a main program in which f1 is used generates a screen output, for example, I can safely exclude f1 as the source of this side effect. If you give me a function `f2 :: Int -> IO Int` instead, I can't draw all these conclusions. In Python, these conclusions would be invalid from the start.
Now you can say, “So what? Who cares?” But it helps me enormously when designing and structuring programs, understanding programs, localizing program behavior, etc. If you don't see any added value in this distinction (ensured by the compiler), we don't have to argue about it. But I simply cannot agree with you that this does not represent a conceptual and formally justified difference between Haskell and Python.
Of course you can program purely functionally in Python. Just as you can program in a dynamically typed language as if you were dealing with static data types. Or in Java without throwing exceptions and null references around everywhere. Or in C without segmentation faults.
These are not normative or moral comparisons, but other examples of the fact that you can of course program in such a way that the code has certain properties, even if the compiler does not secure these properties. The question is whether you want that.
I have mentioned downthread [0] a few characteristics that distinguish FP from other paradigms - namely, first-class functions and higher-order functions (the ability to pass functions to functions); referential transparency, "pure functions" without side effect, and equational reasoning (the ability to replace expressions with their value and keep the behaviour of the program identical); and a tendency to prefer parametric and ad-hoc polymorphism (generics and trait/typeclass bounds) to subtype polymorphism, the "inheritance" boogeyman of OOP.
Again as mentioned in [0] the "expression problem" [2] is a good model for discussing the ergonomics and tradeoffs of FP vs. OOP.
[0] https://news.ycombinator.com/item?id=41450851
It is a case of the paradigm not really meaning anything. It is an arbitrary bunching of language features and code properties that doesn't provide a particularly useful guide. Anything that is a good idea in one paradigm is also a good idea in any other paradigm too.
If you want to see object-orientation taken to the extreme, and how it makes writing programs in a functional style extremely unergonomic, you can read old-school Guava code from Java 6 and try to decipher all the line noise; there is even a caveat in its official documentation [2] that states,
functional programming without Java 8+ requires awkward and verbose use of anonymous classes.
Excessive use of Guava's functional programming idioms can lead to verbose, confusing, unreadable,
and inefficient code. These are by far the most easily (and most commonly) abused parts of Guava,
and when you go to preposterous lengths to make your code "a one-liner," the Guava team weeps.
> It is a case of the paradigm not really meaning anything. It is an arbitrary bunchingThis is a case of throwing the baby out with the bathwater; just because we can't come up with a perfectly precise definition doesn't mean that we should dispense with rough heuristics and (perhaps crudely drawn) boundaries that serve as a useful clustering of related features. Try asking a machine learning or computer vision algorithm for the criteria it uses to categorize something as a "dog;" it's unlikely that you'll come up with something as precise as the definition of the Platonic ideal of a dog, but we can still use its model to recognize dogs with a reasonable degree of accuracy.
[0] https://docs.python.org/3/library/functools.html
[1] https://docs.python.org/3/howto/functional.html#small-functi...
[2] https://github.com/google/guava/wiki/FunctionalExplained
> "functional programming is a programming paradigm where programs are constructed by applying and composing functions"
This is only seems like a useless truism if you take 'function' to mean 'method' or 'procedure'. If you nail down 'function' to sameinput->sameoutput then it starts to make more sense.
So let's say you have this in your code:
x = 1
b = x + 2
x = b + x
You have composed three procedures here in order. This is illegal. You must ONLY construct the programs via composing functions there can be no other way. let x = 1
b = x + 2
x = b + x
in <do something with b and x>
The third line creates a second binding of x which shadows the first binding, and shadowing is considered by most people to be within the functional paradigm. What is not considered functional by most people is assigning a variable in a loop although even here you can do it in Haskell. Specifically, you can call readIORef and writeIORef every loop iteration, but last time I tried, that was about 1000 times less efficient than in an imperative language.And good riddance, too! I'm so sick of seeing this anti-pattern at $DAYJOB: First, create a thing which isn't what you called it (e.g. 'result'), and then mutate it in place until it is what you called it.
I don't think OOP ever had nearly as strong of a mathematical/scholarly foundation as FP has
Can you describe a programming language that isn't based on lambda calculus? It is a universal model of computation.
Consider whether the same input to your code will result in the same output (aka functions), that's a good place to draw the line.
You can stick 'FP' fancy types and closures into a method; that doesn't turn it into a function.
It's also important to teach the techniques together because functional programming tools are typically (deliberately) less powerful, which makes them easier to analyze, but means you need more tools.