Hacker News new | ask | show | jobs
by Hoffenheimer 4772 days ago
Different languages are good at different things. Some are good for pattern matching, others are great for describing algorithms, others are fit well into a specific OS ecosystem, others are good at manipulating specific data structures (such as vectors, matrices, graphs, etc.), and so on.

The most powerful part about pure functional programming is that you get more powerful functions. Because your functions don't change the state of data, you can confidently combine them into new functions, producing a sort of chain effect. This can lead to very concise programs since there is no need to hold intermediate variables (i, count, temp, ...) in some place. What you sometimes end up with are one liners that -- if the functions are named well enough -- explain the entire logic of the program.

There are certain problems that lend themselves well to the functional style, mainly those where you are piping a piece of data through various functions and applying different transformations to it. It's worth learning at least a couple of functional languages so you're not applying a hammer where you need a wrench.

1 comments

> There are certain problems that lend themselves well to the functional style, mainly those where you are piping a piece of data through various functions and applying different transformations to it.

I don't quite understand this - how does this fit into the 'immutability' of fp? So functions can mutate data that goes into them, but they can't maintain internal state?

In FP functions shouldn't mutate data structures that were passed by reference on input, instead any input data should be copied before performing mutations on it to avoid changes to external state.

This is how e.g. Array.prototype.filter() works in JavaScript:

  var numbers = [1,2,3,4,5,6,7,8,9,10];

  var evenNumbers = numbers.filter( function(number) {
    return number % 2 === 0;
  });
I would like to add that this it is perfectly possible to write purely functional programs that do mutation. You just need to be explicit about it.

Many purely functional data structures also have advanced implementations that need much less copying than "immutable" would at first make you think, since two values can share unchanged structure.

It's not really considered "mutation" at all. They just return new values that are related in some way to the input values.
In f# for example you can write: let result = list1 |> List.filter (fun e -> ...) |> List.map (fun e -> ...) |> .... no mutation, but you are piping the intermediate result to the next operation. In c# you could achieve a similar result by using the dot operator instead of the backpiping |> one.