← Back to context

Comment by elbear

12 days ago

What's the benefit?

You start to see functions as self-contained things, as lego blocks. All the logic of the function is there in the function. It only works on values it receives as inputs (it can't read global variables). It only outputs its results (it doesn't assign them to some other global variable that you have to track down).

This makes your code modular. You can add a function in a chain of functions, if you want to perform an extra transformation. Or, you can replace a function with a different one, if you want to change something about the logic.

Is there a benefit if you're already familiar with writing functions like that? Is it wrong for me to expect that most programmers are already familiar with functions that only use their inputs, but treat that style as significantly more optional?

I wrote pure functions for a minute there but that's not the same, a function that only uses its inputs can modify an object while a pure function would have to return a new object. But, similarly, I bet that a lot more people know about pure functions than have any working knowledge of Haskell.

  • It seems you only focused on one of the conditions I mentioned.

    You have to follow both rules: the one about inputs and the one about outputs.

    This is like a contract. If you enforce it throughout your program, you gain some guarantees about your program as a whole.

    • I was looking at both rules, and specifically I was using the long version where you said "it doesn't assign them to some other global variable that you have to track down". If you pass in a mutable object then that's not "some other global variable".

      If I interpret "It only outputs its results" in a very strict way, that still allows having output and in/out parameters. The latter of which can break purity.

      Though you can break purity with just inputs:

        define f(o): return o.x
        let a = {x=1}
        f(a)
        a.x = 2
        f(a)
      

      If you meant to describe pure functions then that's fine, that's why I addressed pure functions too, but I don't think your original description was a description of pure functions.

      12 replies →

  • > Is it wrong for me to expect that most programmers are already familiar with functions that only use their inputs

    They'll experience no friction when using Haskell then. Haskell only refuses to compile when you declare "Oh yeah I know functions from other languages this is easy" but then do some mutation in your implementation.

    • > They'll experience no friction when using Haskell then.

      The question was what benefit you'd get from learning a functional language, though. Existing knowledge making it easier to switch to a functional language is the inverse of that.

      And there's no assumption they'll actually be making things in Haskell, so easy switching isn't by itself a benefit.

      2 replies →