5 ms·
> The core of Functional Programming is thinking about data-flow rather than control-flow I've spent a small amount of time trying to convince people that FP i
by dahart 9y ago
> The core of Functional Programming is thinking about data-flow rather than control-flow
I've spent a small amount of time trying to convince people that FP is a byproduct of immutability and not much else. But I like this description better than that. I like that it captures the idea of dependencies. Data flow, and FP, are about explicitly passing all the required dependencies into any step in the process, and getting back all the results - as opposed to having any implicit inputs or output. Making all dependencies explicit will force you into writing immutable code, and likewise writing exclusively with immutable data and functions that dont have side-effects will automatically make you spit out code with explicit dependencies as a byproduct. These are two sides of the data-flow coin.
I also like that the focus on data-flow makes it clear you can do FP in any language. Some languages definitely help you, but you absolutely can practice data-flow over control-flow in C and assembly almost as easily as python. It's just tempting not to when you don't have to, being more strict about FP takes more self control.
- im_down_w_otp 9y agoI tell people it's about focusing on inputs and outputs rather than worrying about inputs and side-effects. It let's you develop complex programs with clear separation of responsibilities without having to try to keep the model of the entire state-space in your head at once.
- danek 9y agoYeah, I find that pure functions (or pure functions living in immutable objects) makes my code immensely more composable and easier to work with (i.e. more adaptable and less expensive to own). If some business requirement changes I can recompose and tweak existing code without reading every line of code to figure out what side effects may unintentionally get triggered.
- disantlor 9y agoI never really properly learned TDD and always felt a bit bad about it. Then I discovered this side effect (or primary effect) of FP and felt like there was no real need for tests. Not sure if I'm just rationalizing but the ability to drop into the data flow and make changes or add features with confidence makes programming so much more fun.
- hellofunk 9y agoBut without immutable data structures, even in a language like C you end up with a very expensive copying for FP work.
- seanmcdirmid 9y agoImmutability typically requires lots of copying anyways, even in functional languages. There is no free lunch to be had.
- willtim 9y agoI would say that the opportunity to freely share values without needing to defensively copy is of greater benefit, especially with an increasingly multicore future. Updating in-place also requires memory barriers, which don't scale.
- seanmcdirmid 9y agoSurely immutability works well when sharing values that shouldn't change anyways, in functional or other styles of programming. What we are talking about here are immutable data structures that replace mutable ones, where mutability is pushed off to a higher reference cell (so instead of having a mutable set, we have a mutable variable that points to a new immutable version of the set). In both cases, locking is required if thread safety is desired.
- willtim 9y agoWhy do you need a mutable variable? I thought we were discussing functional programming, in which case they should be rarely needed :)
- seanmcdirmid 9y agoIf you want to keep track of world-current, then you need a variable that changes from world-0 to world-1 somewhere. Conceptual mutability (change over time) doesn't go away because you are using immutable data structures.
- barrkel 9y agoThe thing that stops you from doing data-flow freely in C or assembly is ownership of memory. In a GCed language, you can freely your parameters into a complex returned structure; without GC, you can't mix up ownerships without a separate accounting system. Consider: struct some_struct *f(int x, char *y) { struct some_struct *result = malloc(sizeof *result); if (x < 0) result->value = "negative"; else result->value = y; return result; } If you're writing functional code, the return values of your routines will normally be a function of the parameters, which often means wholesale inclusion. Without GC, you need to do a lot more preemptive copying, and freeing the resulting data structures is much more painful. Alternative accounting systems can be used, e.g. arena or marker based allocation (freeing everything allocated when control returns to earlier points on the stack), or something else more involved. But it's not free.
- first_amendment 9y agoC++11 allows you to write natural "value-oriented" code without paying a copying cost. This is thanks to RVO (return value optimization) and move semantics.
- stcredzero 9y agoData flow, and FP, are about explicitly passing all the required dependencies into any step in the process, and getting back all the results I always knew there was some relationship between FP and dataflow. There is something profound here. However, I'm not so sure that current FP languages are capturing this something in the best possible way. To me this: http://www.lihaoyi.com/post/BasicFunctionalProgramming/CodeGraph.png http://www.lihaoyi.com/post/BasicFunctionalProgramming/CodeG... Somehow seems far inferior to this: http://www.lihaoyi.com/post/BasicFunctionalProgramming/DiagramGraph.png http://www.lihaoyi.com/post/BasicFunctionalProgramming/Diagr...
- lilactown 9y agoSome syntactic sugar can help with this a bit; here's the same code rewritten using the pipe operator in Elixir: def make_tiramisu(eggs, sugar1, wine, cheese, cream, fingers, espresso, sugar2, cocoa) beat(eggs) |> beat(sugar1, wine) |> whisk |> beat(beat(cheese)) |> fold(whip(cream)) |> assemble( soak2seconds(fingers, disolve(sugar2, espresso))) |> sift(cocoa) end It reads a lot closer to the recipe, though the nested multiple operations are still a bit hard to read. Separating them into their own named functions would probably be better.
- eyelidlessness 9y agoIn Clojure: (defn make-tiramisu [eggs sugar1 wine cheese cream fingers espresso sugar2 cocoa] (-> eggs (beat) (beat sugar1 wine) (whisk) (beat (beat cheese)) (fold (whip cream)) (assemble (soak2seconds fingers (dissolve sugar2 espresso))) (sift cocoa) (refrigerate)))
- agumonkey 9y agoMy first love was computer graphics and multimedia, the only software I liked were ones that: 1) had features called virtual entities: you don't crunch bytes, you manipulate the concepts, and only when needed you compute 2) non destructive edition: since 1) you can pile up operations without ever fearing loss of information, or memory usage for backup. The first audio editing software I had was Sound Forge, a simple one, every operation meant allocating a new space, computing, filling. This meant limited undo and higher resource requirements 3) from 1 and 2 you get laziness (examples: nothing real shake, sidefx houdini, alias wavefront maya, sekd samplitude, anything by discreet. All these made far better use of your hardware. Compared to famous but non lazy ones such as Sound Forge or 3dsmax .. your poor desktop became pro tool (sic). Well until you hit the final render button of course) Later I discovered FP and I laughed nervously. Also many many highly rated CGI software use dataflow on a lazy DAG. GHC uses this for sharing computation in the evaluation model.
- dwenzek 9y agoAs you, I like the focus on data-flow, but I disagree when you said that: > Making all dependencies explicit will force you into writing immutable code. We have the opposite: Writing immutable code will force you into making all dependencies explicit.
- dahart 9y ago:) You sure you disagree? I said both, and the most important part is it works both ways. That's why I like the data-flow point of view; it more naturally gives rise to thinking about both immutability and explicit dependencies, and helps to avoid arguments over whether immutability is what defines functional programming.
- dwenzek 9y agoIndeed I reacted a bit too quickly ! You are right. You were even going straight to the point when saying that "These are two sides of the data-flow coin."
- chriswarbo 9y ago> I've spent a small amount of time trying to convince people that FP is a byproduct of immutability and not much else. I'm not sure that's true in general; although it seems to hold in FP languages and FP-style in imperative languages, where we have "function-like things" (functions/subroutines/methods/etc.), an implicit 'arrow of time' (a sequence of instructions, irreversible reduction rules, etc.), some notion of "values" which can be passed around, mechanisms for naming/referencing/substitution/etc. and other such "ambient" language features that we might not think about too much since they're present in most mainstream languages. If we step back from this imperative(-like) mainstream though, we find things like Prolog, miniKanren, SQL, Joy, Pure, Maude, Eve, Church, Unlambda, etc. whose semantics are based on relational algebra, answer-set programming, probabilistic programming, theorem proving, term-rewriting, stack models, etc. If we consider mutable vs. immutable variants of these languages, I don't think we'd find that immutability gives rise to FP as a byproduct. For example, relational languages don't have a construct corresponding to functions; they have relations, which are more general since they are many:many rather than many:one. They also don't distinguish between "inputs" and "outputs", which allows relations to be "run backwards" (e.g. using `plus(5, x, 8)` to perform subtraction, with the result `x = 3`); this muddies the 'arrow of time', allowing a single "reduction step" to expand an expression (and perform an arbitrary amount of search in the process!). Such things are perfectly immutable (AFAIK languages like miniKanren enforce immutability, in a similar way to Haskell), yet I wouldn't call them "functional programming". Similarly, the idea of "values" (and therefore referential transparency) can become murky: do we mean that an expression always evaluate to the same object-level term, or that querying an expression always chooses from the same set of possible terms, or that sampling an expression always draws from the same distribution over terms? I've come across this 'murkiness' in the real world via Haskell's popular QuickCheck library, which provides a `Gen` monad that violates the monad laws: when given the same random seed, functions which should be equal may return different values. Yet `Gen` is "morally" a monad, since the probability distribution of those functions across arbitrary seeds is equal: https://hackage.haskell.org/package/QuickCheck-2.10.0.1/docs/Test-QuickCheck-Gen-Unsafe.html https://hackage.haskell.org/package/QuickCheck-2.10.0.1/docs... From the point of view of "writing my language-X project in a more functional style", I think going after immutability captures most of the idea, assuming "language-X" is some popular imperative/FP language. From the point of view of "language-X is functional because...", I don't think immutability captures much of the essence of FP at all.
- cr0sh 9y ago> I also like that the focus on data-flow makes it clear you can do FP in any language. Challenge to anyone who cares: Do FP using Microsoft BASIC, circa 1980 or thereabouts (heck, if you want, use any BASIC from that era). I'm pretty sure FP would be easier to demonstrate using Logo from that period than using BASIC. /carry on...
- bonesss 9y ago> Do FP using Microsoft BASIC, circa 1980 or thereabouts (heck, if you want, use any BASIC from that era). Well... anything without higher order functions & currying is gonna struggle with _beauty_ when it comes to Functional Programming... And Basics type system wouldn't be particularly enjoyable in the context of serious development... That said, and supporting the OPs point: mapping the required functional data transformations, establishing a flow of transformed data, and producing code to support that transformation is highly achievable in typed imperative languages. In fact, it would be right at home in Basic... Creating immutable, side-effect free functions in Basic that are then chained on matching output types and input types, and composing those functions in a control function, would look much closer to "bog standard" Basic than attempting OOP in Basic does. In fact, to a trained imperative Basic developer, it would look like very clean, composable, code that had logical and contained GOTOs and a well-reasoned strict relationship to changing data in incoming parameters... You would not have any language support forcing you to Do The Right Thing, and there would be oodles of temp variables smart FP languages just compose away... but to do FP in MS Basic ca 1980? Just grab some imperative Basic, strip the side effects, and you're done. Basics later modules are a great conceptual match for Haskell and OCamls modules, too... > I'm pretty sure FP would be easier to demonstrate using Logo from that period than using BASIC. Logo is a LISP dialect created to teach (functional) programming and logic, so that claim would apply to lots of languages IMO :) I think the idea that FP isn't highly grokable in imperative languages is a symptom of the biggest problem with functional programming: it's both far simpler than we imagine and more complex.
- GlennS 9y agoDo you remember if GOSUB <label> or GOTO <line number> can take the contents of a variable as an input? If so, then higher-order functions seem possible. Edit: it looks like in at least some versions of basic you can do: ON switching_variable GOSUB first_label, second_label, third_label, ...
- agumonkey 9y agoI do like that too. lambda is just "I need this and that for the body to make sense". I also like that providing partial dependencies isn't an error, but yields a smaller-dependencies lambda (thanks curry I guess). But more and more I go away from functions as a thing. Scheme compiler turn lambdas into goto+args, Prolog made me think of programs as forest/graphs that you walk... and yes if you look at functions as dependencies then you end up as a description of a dep. graph.. so graphs again.