by vortico · 6y ago · 0 comments
for staff in company.staff:
for pet in staff.pets:
if pet.type == 'cat':
print(pet.name + " belongs to " + staff.name)
I don't understand why functional languages are used at all.Now if you restrict yourself to not introduce any side effects, the interpreter can be proven correct, the execution can be analysed much better and you can have some neat safety guarantees.
That's why.
I don't understand what you mean by "analyzed much better" and "neat safety guarantees". Is my code hard to analyze or unsafe?
Functional programmers (of the Haskell bent, at least) would prefer that they not have to write printCatsBelongingToStaff, printCatsBelongingToCustomers, printCatsBelongingToChildrenOfStaff, printDogsBelongingToStaff, renameCatsBelongingToStaff, &c. They would instead prefer to write print, rename, staff, customers, cats, dogs (or perhaps just pets, with an ability to discriminate between cats and dogs...), children, and compose. They would also prefer to write these functions in such a way that the computer (rather than the human) can analyze the resulting compositions and guarantee that they operate in the way you would expect (with "expect" being precisely codified between the types of the functions and a succinct set of laws).
The big picture here is that computers are much faster and more consistent in their checking ability than humans, so the more things we can encode in our programs in a computer-checkable way, or in laws that we can prove are preserved under composition, the more reliable our software will be on whole.
Of course in Python you could parametrize the predicates or the attributes or attribute values, and it would still be fine FP code.
Ah - how about if we add "by the compiler": They can be analyzed much better by the compiler, and we get neat safety guarantees by the compiler.
> Is my code hard to analyze or unsafe?
Not for a human, no :) But optics allow us to drop some boilerplate, retain all flexibility, and also allow the compiler to do a deeper analysis so we can compose computational patterns. That composition composes, so as we build more complex things we have tools with us to help navigate them.
Say we want to reuse your cat search code. Sometimes we want to log it, and sometimes we want to export it as a different data structure.
You could write a function that took a company and returned a list of pets.
What if you wanted to take the first 10 of 10 million. Returning the full list wouldn't be very efficient, you would need to alter your function to support limits.
What if you were then given a list of companies. You would need to modify the function, or write a wrapper.
What if it isn't a list anymore but an async stream of companies. More modifications.
With functional techniques, we can abstract the concept of "filtering a company for pets" without worrying about the concrete implementation of how the returned pets are stored. This allows the one function to be reused efficiently in many different applications, in ways not possible with imperative code.
This is just one example of abstraction that is possible. Functional techniques are not a good fit for all problems, but they are a good tool to have in your toolbox as they make some problems much easier to reason about.
Paul Graham has written a lot on the power of functional languages. OnLisp is a good place to start: http://www.paulgraham.com/onlisp.html
Or some of his early blog posts discuss these concepts: http://www.paulgraham.com/articles.html
Another classic that will change the way you look at code design is Structure and Interpretation of Computer Programs: https://web.mit.edu/alexmv/6.037/sicp.pdf
For loops can be easily mapped into functional constructs, but not your snipped does not compute anything. It's not a function.
The second advantage is conciseness. I don't know if you've actually used jq, but if you have, I really don't know why anyone prefers a verbose for-loop-and-if-statement block over a single concise jq expression. Paul Graham expressed this idea better than I could have so read this: http://www.paulgraham.com/power.html
import optics.for as o_for
o_for company.staff.pets as (.{pet}, optics.parentNode as owner) where (pet.type == "cat"):
print "{.name|%s} belongs to {owner.name|%s}")
We're guaranteed to be safe against null values in company and staff and pets – we don't have to think about it – and no "for" or "if" is required for walking down the structure. Also the types of pet and owner are completely certain, and we can give verified compile-time guarantees that the string we're populating is 100% correct to match the input.This is the very simplest use of optics. Optics also allow us to do express wild things over those structures, such as selecting nodes based on some defined statistical relationship to the statistics of defined parts of the whole structure. It's as simple and concise as the example above. And as efficient as possible.
The fact that method selectors only appear very rarely as first-class values in most languages means that most people aren’t tuned in to scenarios where they could be applied. But I bet you’ve invented special cases of this yourself, when you had a function that needed to dig data out of one of several locations, depending on other inputs.
I know it's easy to forget how much .. stuff .. there is in an imperative language. You have the side-effect in print, and if you replace that with appending a string you're going to invoke the weird and wonderful assignment operator.
It's easy to forget how strange these things (state and side effects) are once you have mastered them in your craft.
The reason I love functional style with immutable data is because it is so dead simple and easy on my tired brain.
{company: {staff: [{..., pets: []}]}}
And what we want to do is to produce a list of all the pet cats with its owner name.
[{cat: "bla", owner: "bla"}...]
or
[{owner: "bla", cats:[...],...}, ...]
So I guess what Im trying to explain is that what is important is the change in the way of thinking about problems. When you think of them as data transformations there is a whole lot of possibilities that open. And it is not more expensive because you even have things like transducers. When you abstract away the iteration you are able to compose much more easily.
And to answer your question directly in my example the print function would print for each cat belonging to the staff which is not great flattening would be more elegant. What I wanted to convey is thinking in data transformations and abstracting away the implementation details of the iteration.
const stf = [
{name: "x", pets: [{type: "cat", name: "kitty"},
{type: "cat", name: "kitty2"}]},
{name: "y", pets: [{type: "dog"}]},
{name: "z", pets: [{type: "cat", name: "miau"}]},
];
const myTransform = ({ pets, name: ownerName }) => pets
.filter(({type}) => type === "cat")
.map(({ name: catName }) => ({ ownerName, catName }))
stf
.map(myTransform)
.flat()
.forEach(({ownerName, catName}) => console.log(`Cat ${catName} to ${ownerName}`))It's all right. In the sense of using a tool when you find yourself constrained perhaps it's worth waiting till you find a problem where you feel "there's got to be a better way".
It's happened to me when I was writing generators/shrinkers for generative tests that operate over any Thrift or Protobuf type.
I strongly dislike hybrids, multiparadigm, metaprogramming, and inheritance-heavy OOAD.
Most of our work is CRUD, meaning data centric. Right?
My arm wavy overgeneratalization is that functional programming promotes functional decomposition style programming, which emphasizes flow of control modeling over data modeling. Especially when noobs go overboard with lambdas, stream processing, reducers, and so forth, which obfuscates the data transformations.
Whereas imperative programming can be more straightforward for simple data processing. Until noobs go overboard with OOAD stuff like inheritance, making wrapper classes for everything, and design pattern overkill. Then the wheels fall off and the engine explodes once someone reads a book about inversion of control, dependency injection, mocking, aspects, or optionals (non-null).
YMMV.
for (owner <- company.staff)
for (pet <- staff.pets if pet.type=="cat")
yield (owner.name, pet.name)
builds a datastructure with the same information yours prints, with no extra boilerplate around building the datastructure.`.company.staff | .pets | flatten | filter .type == "cat" | log(...)`
The original version with for loops just looks like a block of text. Spacing would help, but I would still need to look carefully to pick out the important bits.
You don't want to listen to any specific camp. The best is always in the middle and you are on the right track:
"Pick what is easy to read."
However there is a caveat, which is that functional style is only hard to read at the beginning. Have a look at how modern languages integrate functional programming (see java, C#, C++, etc.).
Java streams are a common example. They make most code much easier to read ONCE you are used to it, because they provide standardized behaviour that is side-effect free. When you write everything in plain syntax, the reader needs to abstract your code in his head, while when using streams, you just know what `filter`, `map`, `reduce`, etc. do and you only need to look at the small customizations. It's easier to read once you are used to it.
However there is a limit and this limit get hit quickly. A lot of people like to make their code as complicated and fancy as possible and reduce every possible line. This is definitely wrong. Code must be easy to understand and change. If you fail that, you are doing it wrong.
This also depends on your environment. If your co-workers don't understand the code you write, you have failed, no matter if your code is "nicer" or not. You either need to write simpler code or educate your co-workers to create common ground.
That's my point. The fact that you didn't include it implies to me that it was too difficult to figure out, and a true implementation would be far more complicated, so it's not a fair comparison.
.company.staff | .pets | flatten | filter .type == "cat" | print(.name + " belongs to " + ..name)That said, I'm presently struggling with AST transformations and other fun stuff in Haskell, so I completely agree with stating it imperatively. It's far, far easier to learn and read simple imperative code.
That's why in my language Tenet[1] I'm trying a hybrid approach: the underlying representation is immutable, but the language uses ordinary control flow and mutation.
Not all functional languages have static typing. Also type checking helps, but saying that if the types check out it just work it pushing it IMO.
No type checker will catch this error:
sqrt :: double -> double
sqrt x = x
sqrt 10The types of the arguments to the function can have value constraints on it, and those constraints can be determined from a value that exists there: the name of the function.
In any case, the more code you put into the type system the higher the chance that your dependent type specification haS a bug in it.
Even the multi-paradigm, late-bound languages that are adding functional programming are adding static typing, e.g. TypeScript and mypy.
> No type checker will catch this error...
Sure, math is hard. In the domain of structural transformations, one's intuition combined with a decent type checker really does work, though.
Especially, I've done large refactorings of complex transformations, tracked down the typing errors, and then been pleasantly surprised when my test-suites passed the first time.
> sqrt :: double -> double
I can use QuickCheck[1]:
prop_Sqrt_Sqr n = sqrt n * sqrt n == abs n
Because it can exploit the type system, it can then plug in various values of Double to see if squaring my square root squares properly.[1]: http://www.cse.chalmers.se/~rjmh/QuickCheck/manual.html
Obviously if the spec says to create a word processor program, and you instead write a flight simulator, the compiler isn't going to correct that mistake.
And leaky "abstractions" that create more problems than they solve but look cooler than doing things the straightforward way.