Tag Info

Hot answers tagged

72

This is called "inlining" and many compilers do this as an optimization strategy in cases where it makes sense. In your particular example, this optimization would save both space and execution time. But if the function was called in multiple places in the program (not uncommon!), it would increase code size, so the strategy becomes more dubious. (And of ...


47

There are two parts to your question: Why have multiple functions at all (instead of replacing function calls with their definition) and why implement those functions with call stacks instead of statically allocating their data somewhere else? The first reason is recursion. Not just the "oh let's make a new function call for every single item in this list" ...


46

By way of explanation, I'm going to borrow some code from this excellent blog post about closures. It's JavaScript, but that's the language most blog posts that talk about closures use, because closures are so important in JavaScript. Let's say you wanted to render an array as an HTML table. You could do it like this: function renderArrayAsHtmlTable ...


34

Classes with interfaces and inheritance present an open world: Anyone can add a new kind of data. For a given interface, there may be classes implementing it all over the world, in different files, in different projects, at different companies. They make it easy to add cases to the data structures, but because the implementations of the interface are ...


19

The purpose of closures is simply to preserve state; hence the name closure - it closes over state. For the ease of further explanation, I'll use Javascript. Typically you have a function function sayHello(){ var txt="Hello"; return txt; } where the scope of the variable(s) is bound to this function. So after execution the variable txt goes out ...


16

Stacks allow us to elegantly bypass the limits imposed by the finite number of registers. Imagine having exactly 26 globals "registers a-z" (or even having only the 7 byte-sized registers of the 8080 chip) And every function you write in this app shares this flat list. A naive start would be to allocate the first few registers to the first function, and ...


15

First of all, there is nothing that is impossible without using closures. You can always replace a closure by an object implementing a specific interface. It's only a matter of brevity and reduced coupling. Second, keep in mind that closures are often used inappropriately, where a simple function reference or other construct would be more clear. You ...


14

There are two main use cases for closures: Asynchrony. Let's say you want to perform a task that will take a while, and then do something when it's done. You can either make your code wait for it to be done, which blocks further execution and can make your program unresponsive, or call your task asynchronously and say "begin this long task in the ...


13

A couple of other examples: Sorting Most sort functions operate by comparing pairs of objects. Some comparison technique is needed. Restricting the comparison to a specific operator means a rather inflexible sort. A much better approach is to receive a comparison function as an argument to the sort function. Sometimes a stateless comparison function works ...


11

Cases which that approach cannot handle: function fib(a) { if(a>2) return fib(a-1)+fib(a-2); else return 1; } function many(a) { for(i = 1 to a) { b(i); };} There are languages and platforms with limited or no call stacks. PIC microprocessors have a hardware stack limited to between 2 and 32 entries. This creates design constraints. COBOL bans ...


10

So does functional programming just add a cleaner syntax that makes this style of programming seem less gross? That is a simplification perhaps, but yes. What else am I missing? Let's be clear on what algebraic data types are (summarizing this fine link from Learn you as Haskell): A sum type that says "this value can be an A or a B". A product ...


9

When doing FP I tend to use more specific semantic types. For example, your method for me would become something like: read: MessageId -> Message This communicates quite a lot more than the OO(/java)-style ThingDoer.doThing() style


8

So, what can functional programmers do to preserve the semantics of a well-named interface? Use well named functions. IMessageQuery::Read: int -> string simply becomes ReadMessageQuery: int -> string or something similar. The key thing to note is that names are only contracts in the loosest sense of the word. They only work if you and another ...


7

Closures are equivalent to objects implementing a run() method, and inversely, objects can be emulated with closures. The advantage of closures is that they can be used easily anywhere you expect a function: a.k.a. higher-order functions, simple callbacks (or Strategy Pattern). You don't need to define an interface/class to build ad-hoc closures. The ...


7

You want function inlining, and most (optimizing) compilers are doing that. Notice that inlining requires the called function to be known (and is effective only if that called function is not too big), since conceptually it is substituting the call by the rewriting of the called functgion. So you generally cannot inline an unknown function (e.g. a function ...


6

Inlining (replacing function calls with equivalent functionality) works well as an optimization strategy for small simple functions. The overhead of a function call can be effectively traded off for a small penalty in added program size (or in some cases, no penalty at all). However, large functions which in turn call other functions could lead to an ...


6

Nothing that hasn't been said already, but maybe a simpler example. Here's a JavaScript example using timeouts: // Example function that logs something to the browser's console after a given delay function delayedLog(message, delay) { // this function will be called when the timer runs out var fire = function () { console.log(message); // closure ...


5

SQL is based on Relational Algebra and Tuple Relational Calculus, not higher-order functions or functional programming. While SELECT, FROM and WHERE have analogous functions in other languages, SQL itself doesn't support generalized higher order functions, but only those "higher-order" functions that the language itself defines. Since SQL doesn't allow ...


5

As Telastyn says, comparing the static definitions of functions: public string Read(int id) { /*...*/ } to let read (id:int) = //... You haven't really lost anything going from OOP to FP. However, this is only part of the story, because functions and interfaces aren't only referred to in their static definitions. They're also passed around. So let's ...


4

You seems to want to make some optimization (e.g. common subexpression extraction, as commented by rwong) in your interpreter. Notice also that a language (even a domain-specific language) is never defined by some internal representation, but a computer language is defined by its syntax and its semantics (so you'll better define them first, at least on ...


3

It may surprise you to learn that pattern matching is not considered the most idiomatic way to work with Options. See the documentation of Scala's Options for more about that. I'm not sure why so many FP tutorials encourage this usage. Mostly what you're missing is there are a whole bunch of functions created to make working with Options easier. Consider ...


3

Have a look at LINQ, which takes the basic concepts behind SQL and generalizes it to object-oriented programming. The Where operator is a bog-standard Filter, the Select operator is a projection/Map, and so on. All of the basic SQL query operations are represented in LINQ, implemented using higher-order functions, so yes, you're correct in your intuitive ...


3

How can varargs be implemented? We need some mechanism to signal the end of the argument list. This can either be a special terminator value, or the length of the vararg list passed as an extra parameter. Both of these mechanisms can be used in the context of currying to implement varargs, but proper typing becomes a major issue. Let's assume that we are ...


3

PHP can be used to help to show a real example in a different language. protected function registerRoutes($dic) { $router = $dic['router']; $router->map(['GET','OPTIONS'],'/api/users',function($request,$response) use ($dic) { $controller = $dic['user_api_controller']; return $controller->findAllAction($request,$response); ...


2

Is there still any functional programming language that doesn't rely on C runtime? Yes (at least if you consider (like I do) that Lisp variants are functional languages (because they have the application and abstraction operators of the lambda-calculus), and that any language with closures and abstraction is functional: Bones is an implementation of ...


2

I know that one way to implement this is to recompute the state each time a change arrives, however this seems impractical. If the changes applied when an event occurs are not distributive, in one way or another, you will have to recompute the state each time an event occurs, since the final state is nothing but the initial state, plus successive ...


1

There's really no reason to convert away from degrees. Just do a simple comparison: if abs(lat1 - lat2) < lat_threshold and abs(long1 - long2) < long_threshold: The trick is in setting appropriate thresholds. This will vary depending on your location, but for your purpose could be considered constant across a metropolitan area, so you can ...


1

As I understand the problem you want to associate the position/time data from the device with a bus. presumably you have the timetable information server side, so you know how many buses there are and roughly what times they are at the various stops. you have multiple position/time/device messages with a degree of error in the position/time measurement ...


1

You say you have 2 functions: apply_change::Change -> DataStructure -> DataStructure is_ready::DataStructure ->Boolean and if I understand you right then is_ready is rather expensive so you don't want to do that for every change event over and over. What you need is a function takes an initial DataStructure and condenses it into a simple state ...


1

I will say that it's not limited to functional programming, it's more related to the goal of the project. By using predicate logic (higher order logic) you can create prove for the logic used in the requirement. Translating the logic into functional languages is probably easier. It's also possible to then translate the proven functional language ...



Only top voted, non community-wiki answers of a minimum length are eligible